How to Nest one Array within Another Array in JavaScript

Posted by

In JavaScript, arrays are a type of object that can store multiple values in a single variable. One way to create a nested array is to create an array and then store another array as an element within that array. For example:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

// Create the outer array
let outerArray = [1, 2, 3];

// Create the inner array
let innerArray = ['a', 'b', 'c'];

// Push the inner array as an element of the outer array
outerArray.push(innerArray);

[/dm_code_snippet]

This creates an outer array with three elements (1, 2, 3), and the last element of the outer array is an inner array containing three elements (‘a’, ‘b’, ‘c’).

Another way to create a nested array is to use array literals to define the elements of the outer array as inner arrays.

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let nestedArray = [[1, 2, 3], ['a', 'b', 'c']];

[/dm_code_snippet]

You can access elements of the inner array by providing two sets of square brackets and the index of the inner and outer arrays

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

console.log(nestedArray[0][1]); //Output 2
console.log(nestedArray[1][1]); //Output 'b'

[/dm_code_snippet]

You can also use loops or other methods to work with nested arrays and perform operations on the elements they contain.

Also you can use concat() method to merge 2 arrays inside outer array

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let outerArray1 = [1,2,3];
let outerArray2 = [4,5,6];
let outerArray3 = [7,8,9];
let outerArray = outerArray1.concat(outerArray2,outerArray3);
console.log(outerArray); //[1,2,3,4,5,6,7,8,9]

[/dm_code_snippet]

You can use the push() method to add elements to the end of an array. When you call push() on an array and pass another array as the argument, the entire inner array is added as a single element to the outer array.

You can also use the splice() method to add an element to a specific index of an array. The splice() method takes three arguments: the index at which to add the element, the number of elements to remove (use 0 if you don’t want to remove any elements), and the element to add.

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let outerArray = [1, 2, 3];
let innerArray = ['a', 'b', 'c'];
outerArray.splice(1, 0, innerArray);

[/dm_code_snippet]

This adds the innerArray to index 1, no elements are removed from outerArray, so the new outerArray will look like [1, innerArray, 2, 3].

You can use nested loops to iterate through the elements of a nested array. You can use the for loop for that

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let nestedArray = [[1, 2, 3], ['a', 'b', 'c']];
for (let i = 0; i < nestedArray.length; i++) {
    for (let j = 0; j < nestedArray[i].length; j++) {
        console.log(nestedArray[i][j]);
    }
}

[/dm_code_snippet]

You can also use the map() and forEach() method to go through the inner arrays.

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let nestedArray = [[1, 2, 3], ['a', 'b', 'c']];
nestedArray.forEach(innerArray => {
    innerArray.forEach(element => {
        console.log(element);
    });
});

[/dm_code_snippet]

You can also use the spread operator(…) to merge 2 nested arrays in JS. It works similar to concat() method

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let outerArray1 = [1,2,3];
let outerArray2 = [4,5,6];
let outerArray = [...outerArray1,...outerArray2];
console.log(outerArray); //[1,2,3,4,5,6]

[/dm_code_snippet]

In addition to the methods I previously mentioned, there are a few more ways to work with nested arrays in JavaScript:

  • The flat() method: This method can be used to flatten nested arrays. It takes an optional argument that specifies the level of nesting to flatten. If no argument is provided, it will flatten the array to the maximum level.

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let nestedArray = [[1, 2, 3], [4, [5, 6]], ['a', 'b', 'c']];
let flatArray = nestedArray.flat();
console.log(flatArray); // [1, 2, 3, 4, [5, 6], 'a', 'b', 'c']

[/dm_code_snippet]

  • The flatMap() method: This method applies a function to each element of an array and then flattens the resulting arrays into a new array.

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let nestedArray = [[1, 2], [3, 4], [5, 6]];
let flatMappedArray = nestedArray.flatMap(innerArray => innerArray.map(x => x * 2));
console.log(flatMappedArray); // [2, 4, 6, 8, 10, 12]

[/dm_code_snippet]

  • Using JSON.stringify() and JSON.parse() : These methods allow you to convert JavaScript objects, including arrays, to and from a JSON string. This can be useful if you need to store or transmit nested arrays in a string format.

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let nestedArray = [[1, 2, 3], ['a', 'b', 'c']];
let jsonString = JSON.stringify(nestedArray);
let parsedArray = JSON.parse(jsonString);
console.log(parsedArray); // [[1, 2, 3], ['a', 'b', 'c']]

[/dm_code_snippet]

  • reduce() method : This method can be used to iterate through an array and reduce it to a single value. You can use this method to iterate through a nested array, and perform some operation on each element.

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let nestedArray = [[1, 2, 3], ['a', 'b', 'c']];
let total = nestedArray.reduce((acc, innerArray) => {
    return acc + innerArray.reduce((acc, el) => acc + el);
}, 0);
console.log(total); //6 (1+2+3)

[/dm_code_snippet]

In addition to these methods, you can use the indexOf() method to find the index of an element within a nested array, or use the find() and filter() methods to return specific elements from a nested array based on certain conditions.

As you can see, there are many ways to work with nested arrays in JavaScript. The best approach will depend on the specific use case, and it’s always important to consider the performance of your code when working with large arrays.