Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge/flatten an array of arrays

I have a JavaScript array like:

[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]] 

How would I go about merging the separate inner arrays into one like:

["$6", "$12", "$25", ...] 
like image 336
Andy Avatar asked Jun 02 '12 18:06

Andy


People also ask

How do you combine array arrays?

To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.

Can you flatten an array?

To flatten an array means to reduce the dimensionality of an array. In simpler terms, it means reducing a multidimensional array to a specific dimension. let arr = [[1, 2],[3, 4],[5, 6, 7, 8, 9],[10, 11, 12]]; and we need to return a new flat array with all the elements of the nested arrays in their original order.

What is a nested array?

Nested Array in JavaScript is defined as Array (Outer array) within another array (inner array). An Array can have one or more inner Arrays. These nested array (inner arrays) are under the scope of outer array means we can access these inner array elements based on outer array object name.


1 Answers

You can use concat to merge arrays:

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

Using the apply method of concat will just take the second parameter as an array, so the last line is identical to this:

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

There is also the Array.prototype.flat() method (introduced in ES2019) which you could use to flatten the arrays, although it is only available in Node.js starting with version 11, and not at all in Internet Explorer.

const arrays = [        ["$6"],        ["$12"],        ["$25"],        ["$25"],        ["$18"],        ["$22"],        ["$10"]      ];  const merge3 = arrays.flat(1); //The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.  console.log(merge3);      
like image 183
Gumbo Avatar answered Oct 13 '22 12:10

Gumbo