Skip to content

JavaScript Array of Arrays | Codes

  • by

In JavaScript, an Array of Arrays is called a Multidimensional Array. JavaScript does not provide the multidimensional array natively. But, you can create a multidimensional array by defining an array of elements, where each element is also another array.

// multidimensional array
const data = [[1, 2, 3], [10, 20, 30], [100, 200, 300]];

JavaScript array of arrays

A simple example code creates a Multidimensional Array.

<!DOCTYPE html>
<html>
<body>
  <script>
    let stu1 = [['Jack', 20], ['Sara', 30], ['Peter', 40]];
    console.log(stu1)

    //OR
    let s1 = ['A', 1];
    let s2 = ['B', 2];
    let s3 = ['C', 3];

    // multidimensional array
    let studentsData = [s1, s2, s3];
    console.log(studentsData)
  </script>

</body>
</html>

Output:

JavaScript Array of Arrays | Codes

Access the elements of a multidimensional array using indices (0, 1, 2 …).

<script>
    let x = [['Jack', 20], ['Sara', 30], ['Peter', 40]];
    console.log(x[0]); //[ "Jack", 20 ]
    console.log(x[0][0]); // Jack
    console.log(x[2][1]); // 40
</script>

use the Array’s push() method or an indexing notation to add elements to a multidimensional array.

let s= [['Jack', 24], ['Sara', 23],];
s.push(['New', 100]);

console.log(s); //[["Jack", 24], ["Sara", 23], ["New", 100]

Read more: Multidimensional array.

Merge/flatten an array of arrays

You can use concat to merge arrays:

var arrays = [
  ["$6"],
  ["$12"],
  ["$25"],
  ["$25"],
  ["$18"],
  ["$22"],
  ["$10"]
];
var merged = [].concat.apply([], arrays);

console.log(merged);

Output: [ “$6”, “$12”, “$25”, “$25”, “$18”, “$22”, “$10” ]

How do you find value in a JavaScript array of arrays?

Answer: Use Array.filter() to get a variety of items that match the criteria, or Array.find() the get the 1st item that matches.

const arr = [[false, 1, "label1", "value1", null],[false, 2, "label2", "value2", null]]
const checkNum = 1

console.log(arr.filter(({ 1: n }) => n === checkNum)) // array of items
console.log(arr.find(({ 1: n }) => n === checkNum)) // 1st item found

Output:

find value in a JavaScript array of arrays

Do comment if you have any doubts or suggestions on this JS array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading