How to use map() method In Javascript

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);


Output

[ [ [ 1, 2, 3 ] ], [ [ 'a', 'b', 'c' ] ], [ [ true, false ] ] ]

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

Similar Reads

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....

Method 2: Using reduce() method

...

Method 3: Using from() 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()....

Contact Us