Merge/flatten an array of arrays

typescript flatten(array)
javascript flatten(array of objects)
array.flat is not a function
array flat polyfill
flatten array of arrays python
lodash flatten array
flatten(array javascript es6)
flat is not a function

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", ...]

For Scala users looking for a way to replicate Seq.flatten in Javascript, here is a pimp of Array:

Array.prototype.flatten = function() {
  return [].concat.apply([], this);
};

which can be used this way:

[[12, 3, 5], [1], [], [3, 4]].flatten() // [12, 3, 5, 1, 3, 4]

Array.prototype.flat(), These are the three known ways to merge multidimensional array into a single array. Flattening an array of arrays. Say you have an array of arrays full of objects you want to flatten into one array: You can combine the power of a new Array, the concat function, and the spread operator to create a new array with all of the objects contained within it: const flattenedArray = [].concat(nestedArrays);

I answer this question just with ES6, assume the deep array is:

const deepArray = ['1',[['a'],['b']],[2],[[[['4',[3,'c']]]],[5]]];

If you know or guess the depth of your arrays is not more than a number like 7, use below code:

const flatArray = deepArray.flat(7);

But if you don't know the depth of your deep arrays or your JavaScript engine doesn't support flat like react-native JavaScriptCore, use below function that is used JavaScript reduce function:

 const deepFlatten = arr =>
         arr.reduce(
           (acc, val) =>
             Array.isArray(val) 
               ? acc.concat(deepFlatten(val)) 
               : acc.concat(val),
             []
         );

Both of methods return below result:

["1", "a", "b", 2, "4", 3, "c", 5]

Flattening multidimensional Arrays in JavaScript, Code sample for Programming: const arrays = [[1], ["2"], [3]];const merged = [].​concat(arrays);console.log(merged); // [ 1, '2', 3 ] Pre ES6: var merged  Please note: When Function.prototype.apply ([].concat.apply([], arrays)) or the spread operator ([].concat(arrays)) is used in order to flatten an array, both can cause stack overflows for large arrays, because every argument of a function is stored on the stack.

I have a simple solution without using in a special js function. (like reduce etc)

const input = [[0, 1], [2, 3], [4, 5]]
let flattened=[];

for (let i=0; i<input.length; ++i) {
    let current = input[i];
    for (let j=0; j<current.length; ++j)
        flattened.push(current[j]);
}

Flatten array of arrays with JavaScript, It was always complicated to flatten an array in #JavaScript. Not anymore! ES2019 introduced a new method that flattens arrays. with flat and flatMap · Flatten array of arrays with JavaScript · Stack Overflow: Merge/flatten an array of arrays  Concat is a nice little method that merges two or more arrays by making a copy of the function receiver and merging the arguments into it. It will also merge a single value into an array that it is

Much simpler and straight-forward one; with option to deep flatten;

const flatReduce = (arr, deep) => {
    return arr.reduce((acc, cur) => {
        return acc.concat(Array.isArray(cur) && deep ? flatReduce(cur, deep) : cur);
    }, []);
};

console.log(flatReduce([1, 2, [3], [4, [5]]], false)); // =>  1,2,3,4,[5]
console.log(flatReduce([1, 2, [3], [4, [5, [6, 7, 8]]]], true)); // => 1,2,3,4,5,6,7,8

Flatten Array using Array.flat() in JavaScript - DailyJS, Next: Write a JavaScript program to compute the union of two arrays. What is the difficulty level of this exercise? Easy Medium Hard.   So here's the quick rule. If you know you're dealing with arrays, use spread. But if you might be dealing with the possibility with a non-array, then use concat to merge an array 👍 Anyways I just want to point that out, so you can use the most appropriate method depending on the problem you're trying to solve 👍 # Merge Array with Push 🤔

You can just keep on using Array.flat() method to achieve this even when array is a lot more nested.

[1,2,3,[2]].flat() 

is equivalent to

[1,2,3,[2]].flat(1)

so as your nesting increases you can keep on increasing number.

eg:

[1,[2,[3,[4]]]].flat(3) // [1, 2, 3, 4]

And if you are not sure about level of nesting you can just pass Infinity as parameter

[1,2,3,[2,[3,[3,[34],43],[34]]]].flat(Infinity) //[1, 2, 3, 2, 3, 3, 34, 43, 34]

JavaScript array: Flatten a nested array, Say you have an array of arrays full of objects you want to flatten into one array: +​. const nestedArrays: Person[][] = [ [ {firstName: "Andrew", lastName: "Smith"},  The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

Flattening array of arrays · TypeScript Cookbook, Merge Arrays in one with ES6 Array spread. GitHub Gist: instantly I've noticed a quirk behavior with spread for flattening an array of arrays. With concat it goes  How do I concatenate or merge arrays in Swift? Ask Question Asked 5 years, 8 months ago. Active 10 months ago. Merge/flatten an array of arrays. Hot Network Questions

Merge Arrays in one with ES6 Array spread · GitHub, flat but can be used to flatten nested iterables as well as plain (untyped) arrays. Array(3) [1, 2, 3]. I came across this same issue and found a solution that combines 1-D numpy arrays of variable length: np.column_stack(input_list).ravel() See numpy.column_stack for more info.

d3.merge / D3 / Observable, array. Merges the elements of one or more arrays together so that the values of If an array key exists in both arrays, then the element from the first array will be  As you can see, we first use Zip to take one element from each of the lists, and combine them into a small array of two elements, and then flatten all those arrays using SelectMany. This ends up exactly with the result we want.

Comments
  • gist.github.com/Nishchit14/4c6a7349b3c778f7f97b912629a9f228 This link describe ES5 & ES6 flatten
  • All of the solutions that use reduce + concat are O((N^2)/2) where as a accepted answer (just one call to concat) would be at most O(N*2) on a bad browser and O(N) on a good one. Also Denys solution is optimized for the actual question and upto 2x faster than the single concat. For the reduce folks it's fun to feel cool writing tiny code but for example if the array had 1000 one element subarrays all the reduce+concat solutions would be doing 500500 operations where as the single concat or simple loop would do 1000 operations.
  • Simply user spread operator [].concat(...array)
  • @gman how is reduce + concat solution O((N^2)/2)? stackoverflow.com/questions/52752666/… mentions a different complexity.
  • This doesn't work if the array contains a string which contains a comma. For example, [['test,test'], ['test']].join().split(',') gives ['test', 'test', 'test'] instead of ['test,test', 'test'].
  • I understand it but comma is just an separator. if you want you can use any other which is for sure not be part of json. or you can use combination of special characters as separator. that's logical right. any ways thanks for down voting @MichałPerłakowski
  • I normally use some jibberish, a pattern that is impossible in the dataset.
  • @MichałPerłakowski I hope this fits better for all Array type. I found it on twitter and looks worth updating here.
  • to flat higher dimensional arrays you simply can call the flat method with Infinity argument. Like this: arr.flat(Infinity)
  • That's a very nice addition, thanks Mikhail!
  • The code in the demo doesn't make sense, unless explained.
  • FYI, extending the native Array's prototype is generally discouraged.
  • That's really a misleading variable name :D