![]() |
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 Method 1: Using map() methodThis 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
Output
[ [ [ 1, 2, 3 ] ], [ [ 'a', 'b', 'c' ] ], [ [ true, false ] ] ] Method 2: Using reduce() methodIn 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
Output
[ [ [ 1, 2, 3 ] ], [ [ 'a', 'b', 'c' ] ], [ [ true, false ] ] ] Method 3: Using from() methodIn 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
Output
[ [ [ 1, 2, 3 ] ], [ [ 'a', 'b', 'c' ] ], [ [ true, false ] ] ] |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 10 |