How to Create Nested Arrays from a Nest of Arrays in JavaScript ?
Creating nested arrays from a nest of arrays in JavaScript involves organizing multiple arrays into a hierarchical structure, which is often useful for managing and representing complex data relationships. This process entails encapsulating arrays within other arrays to form multi-dimensional structures. Such nested arrays can represent various data structures, from simple lists of lists to more intricate tree-like structures.
These are the following methods:
Table of Content
- Using map() method
- Using reduce() method
- Using from() method
Method 1: Using map() method
This map method is used to iterate over the input arrays using map(), and for each array, creating a new array containing the original array as its only element. The push() method is then used to append each new array to a resulting array.
Example: Creating the nested array from the given in arrays using the map method.
Javascript
function createNestedArray(...arrays) { return arrays.map(array => [array]); } // Example usage: const arr1 = [1, 2, 3]; const arr2 = [ 'a' , 'b' , 'c' ]; const arr3 = [ true , false ]; const nestedArray = createNestedArray(arr1, arr2, arr3); console.log(nestedArray); |
[ [ [ 1, 2, 3 ] ], [ [ 'a', 'b', 'c' ] ], [ [ true, false ] ] ]
Method 2: Using reduce() method
In this approch, reduce() is used to iterate over the input arrays. For each array, a new array containing the original array as its only element is created and appended to the accumulating result array using push().
Example: Creating the nested array from the given in arrays using the reduce method.
Javascript
function createNestedArray(...arrays) { return arrays.reduce((acc, curr) => { acc.push([curr]); return acc; }, []); } // Example usage: const arr1 = [1, 2, 3]; const arr2 = [ 'a' , 'b' , 'c' ]; const arr3 = [ true , false ]; const nestedArray = createNestedArray(arr1, arr2, arr3); console.log(nestedArray); |
[ [ [ 1, 2, 3 ] ], [ [ 'a', 'b', 'c' ] ], [ [ true, false ] ] ]
Method 3: Using from() method
In this method, from() is utilised to create a new array from the input arrays. A mapping function passed to from() constructs new arrays, with each original array nested within another array. This method offers a concise way to create nested arrays from existing arrays.
Example: Creating the nested array from the given in arrays using the from method.
Javascript
function createNestedArray(...arrays) { return Array.from(arrays, array => [array]); } // Example usage: const arr1 = [1, 2, 3]; const arr2 = [ 'a' , 'b' , 'c' ]; const arr3 = [ true , false ]; const nestedArray = createNestedArray(arr1, arr2, arr3); console.log(nestedArray); |
[ [ [ 1, 2, 3 ] ], [ [ 'a', 'b', 'c' ] ], [ [ true, false ] ] ]
Contact Us