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", ...]
You can use "join()" and "split()":
let arrs = [
["$6"],
["$12"],
["$25"],
["$25"],
["$18"],
["$22"],
["$10"]
];
let newArr = arrs.join(",").split(",");
console.log(newArr); // ["$6", "$12", "$25", "$25", "$18", "$22", "$10"]
In addition, you can use "toString()" and "split()" as well:
let arrs = [
["$6"],
["$12"],
["$25"],
["$25"],
["$18"],
["$22"],
["$10"]
];
let newArr = arrs.toString().split(",");
console.log(newArr); // ["$6", "$12", "$25", "$25", "$18", "$22", "$10"]
However, both two ways above don't work properly if string contains commas:
"join()" and "split()":
let arrs = [
["$,6"],
["$,12"],
["$2,5"],
["$2,5"],
[",$18"],
["$22,"],
["$,1,0"]
];
let newArr = arrs.join(",").split(",");
console.log(newArr);
// ["$", "6", "$", "12", "$2", "5", "$2", "5", "", "$18", "$22", "", "$", "1", "0"]
"toString()" and "split()":
let arrs = [
["$,6"],
["$,12"],
["$2,5"],
["$2,5"],
[",$18"],
["$22,"],
["$,1,0"]
];
let newArr = arrs.toString().split(",");
console.log(newArr);
// ["$", "6", "$", "12", "$2", "5", "$2", "5", "", "$18", "$22", "", "$", "1", "0"]
Here is the recursive way...
function flatten(arr){
let newArray = [];
for(let i=0; i< arr.length; i++){
if(Array.isArray(arr[i])){
newArray = newArray.concat(flatten(arr[i]))
}else{
newArray.push(arr[i])
}
}
return newArray;
}
console.log(flatten([1, 2, 3, [4, 5] ])); // [1, 2, 3, 4, 5]
console.log(flatten([[[[1], [[[2]]], [[[[[[[3]]]]]]]]]])) // [1,2,3]
console.log(flatten([[1],[2],[3]])) // [1,2,3]
function flatten(input) {
let result = [];
function extractArrayElements(input) {
for(let i = 0; i < input.length; i++){
if(Array.isArray(input[i])){
extractArrayElements(input[i]);
}else{
result.push(input[i]);
}
}
}
extractArrayElements(input);
return result;
}
// let input = [1,2,3,[4,5,[44,7,8,9]]];
// console.log(flatten(input));
// output [1,2,3,4,5,6,7,8,9]
Here is the fastest solution in Typescript, which works also on arrays with multiple levels of nesting:
export function flatten<T>(input: Array<any>, output: Array<T> = []): Array<T> {
for (const value of input) {
Array.isArray(value) ? flatten(value, output) : output.push(value);
}
return output;
}
and than:
const result = flatten<MyModel>(await Promise.all(promises));
Well if your coding environment supports ES6 (ES2015), you need not write any recursive functions or use array methods like map, reduce etc.
A simple spread operator (...) will help you flatten an Array of arrays into a single Array
eg:
const data = [[1, 2, 3], [4, 5],[2]]
let res = []
data.forEach(curSet=>{
res = [...res,...curSet]
})
console.log(res) //[1, 2, 3, 4, 5, 2]
I am using this method to flat mixed arrays: (which seems easiest for me). Wrote it in longer version to explain steps.
function flattenArray(deepArray) {
// check if Array
if(!Array.isArray(deepArray)) throw new Error('Given data is not an Array')
const flatArray = deepArray.flat() // flatten array
const filteredArray = flatArray.filter(item => !!item) // filter by Boolean
const uniqueArray = new Set(filteredArray) // filter by unique values
return [...uniqueArray] // convert Set into Array
}
// shorter version:
const flattenArray = (deepArray) => [...new Set(deepArray.flat().filter(item=>!!item))]
flattenArray([4,'a', 'b', [3, 2, undefined, 1], [1, 4, null, 5]])) // 4,'a','b',3,2,1,5
Use of [].flat(Infinity) method
const nestedArray = [1,[2,[3],[4,[5,[6,[7]]]]]]
const flatArray = nestedArray.flat(Infinity)
console.log(flatArray)
It looks like this looks like a job for RECURSION!
Code:
var flatten = function(toFlatten) {
var isArray = Object.prototype.toString.call(toFlatten) === '[object Array]';
if (isArray && toFlatten.length > 0) {
var head = toFlatten[0];
var tail = toFlatten.slice(1);
return flatten(head).concat(flatten(tail));
} else {
return [].concat(toFlatten);
}
};
Usage:
flatten([1,[2,3],4,[[5,6],7]]);
// Result: [1, 2, 3, 4, 5, 6, 7]
flatten(new Array(15000).fill([1])) throws Uncaught RangeError: Maximum call stack size exceeded and freezed my devTools for 10 secondsI propose two short solutions without recursion. They are not optimal from a computational complexity point of view, but work fine in average cases:
let a = [1, [2, 3], [[4], 5, 6], 7, 8, [9, [[10]]]];
// Solution #1
while (a.find(x => Array.isArray(x)))
a = a.reduce((x, y) => x.concat(y), []);
// Solution #2
let i = a.findIndex(x => Array.isArray(x));
while (i > -1)
{
a.splice(i, 1, ...a[i]);
i = a.findIndex(x => Array.isArray(x));
}
The logic here is to convert input array to string and remove all brackets([]) and parse output to array. I'm using ES6 template feature for this.
var x=[1, 2, [3, 4, [5, 6,[7], 9],12, [12, 14]]];
var y=JSON.parse(`[${JSON.stringify(x).replace(/\[|]/g,'')}]`);
console.log(y)
const flatten = function (A) { return A .toString() .split(',') .reduce( (a,c) => { let i = parseFloat(c); c = (!Number.isNaN(i)) ? i : c; a.push(c); return a; }, []); Here is a version in Typescript based on the answer by artif3x, with a bonus implementation of flatMap for Scala fans.
function flatten<T>(items: T[][]): T[] {
return items.reduce((prev, next) => prev.concat(next), []);
}
function flatMap<T, U>(items: T[], f: (t: T) => U[]): U[] {
return items.reduce((prev, next) => prev.concat(f(next)), new Array<U>());
}
Here's another deep flatten for modern browsers:
function flatten(xs) {
xs = Array.prototype.concat.apply([], xs);
return xs.some(Array.isArray) ? flatten(xs) : xs;
};
Nowadays the best and easy way to do this is joining and spliting the array like this.
var multipleArrays = [["$6","$Demo"], ["$12",["Multi","Deep"]], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"], ["$0"], ["$15"],["$3"], ["$75"], ["$5"], ["$100"], ["$7"], ["$3"], ["$75"], ["$5"]]
var flattened = multipleArrays.join().split(",")
This solution works with multiple levels and is also oneliner.
EDIT for ECMAScript 6
Since ECMAScript 6 has been standardized, you can change the operation [].concat.apply([], arrays); for [].concat(...arrays);
var flattened = [].concat(...input);
EDIT Most Efficient solution
The most efficient way to solve the problem is using a loop. You can compare the "ops/sec" velocity here
var flattened=[];
for (var i=0; i<input.length; ++i) {
var current = input[i];
for (var j=0; j<current.length; ++j)
flattened.push(current[j]);
}
Hope It Helps
[[","]].join().split(",") doesn't give desired result.const flatten = array => array.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []);
Per request, Breaking down the one line is basically having this.
function flatten(array) {
// reduce traverses the array and we return the result
return array.reduce(function(acc, b) {
// if is an array we use recursion to perform the same operations over the array we found
// else we just concat the element to the accumulator
return acc.concat( Array.isArray(b) ? flatten(b) : b);
}, []); // we initialize the accumulator on an empty array to collect all the elements
}
Array.isArray(b) in to b.length and add a Array.from(array) after the return instead of array.It's better to do it in a recursive way, so if still another array inside the other array, can be filtered easily...
const flattenArray = arr =>
arr.reduce(
(res, cur) =>
!Array.isArray(cur)
? res.concat(cur)
: res.concat(flattenArray(cur)), []);
And you can call it like:
flattenArray([[["Alireza"], "Dezfoolian"], ["is a"], ["developer"], [[1, [2, 3], ["!"]]]);
and the result isas below:
["Alireza", "Dezfoolian", "is a", "developer", 1, 2, 3, "!"]
Just to add to the great solutions. I used recursion to solve this.
const flattenArray = () => {
let result = [];
return function flatten(arr) {
for (let i = 0; i < arr.length; i++) {
if (!Array.isArray(arr[i])) {
result.push(arr[i]);
} else {
flatten(arr[i])
}
}
return result;
}
}
Test results: https://codepen.io/ashermike/pen/mKZrWK
I have just try to solve the problem without using any inbuild function.
var arr = [1, 3, 4, 65, [3, 5, 6, 9, [354, 5, 43, 54, 54, 6, [232, 323, 323]]]];
var result = [];
function getSingleArray(inArr) {
for (var i = 0; i < inArr.length; i++) {
if (typeof inArr[i] == "object") {
getSingleArray(inArr[i]); // Calling Recursively
} else {
result.push(inArr[i]);
}
}
}
getSingleArray(arr);
console.log(result); // [1, 3, 4, 65, 3, 5, 6, 9, 354, 5, 43, 54, 54, 6, 232, 323, 323]
Here is the solution non recursive flatten deep using a stack.
function flatten(input) {
const stack = [...input];
const res = [];
while (stack.length) {
const next = stack.pop();
if (Array.isArray(next)) {
stack.push(...next);
} else {
res.push(next);
}
}
return res.reverse();
}
const arrays = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]];
flatten(arrays);
if your array only consists out of integers or strings you can use this dirty hack:
var arr = [345,2,[34],2,[524,[5456]],[5456]];
var flat = arr.toString().split(',');
Works, in FF, IE and Chrome didn't test the other browsers yet.
.toString() function (.toString will call for me .toString recursively) which if I recall correctly returned previously "[object Array]" instead of a recursive arr.join(',') :)There's a much faster way of doing this than using the merge.concat.apply() method listed in the top answer, and by faster I mean more than several orders of magnitude faster. This assumes your environment has access to the ES5 Array methods.
var array2d = [
["foo", "bar"],
["baz", "biz"]
];
merged = array2d.reduce(function(prev, next) {
return prev.concat(next);
});
Here's the jsperf link: http://jsperf.com/2-dimensional-array-merge
concat is not only slower, it’s asymptotically slower.I'm aware that this is hacky, but the must succinct way I know of to flatten an array(of any depth!) of strings(without commas!) is to turn the array into a string and then split the string on commas:
var myArray =[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"], ["$0"], ["$15"],["$3"], ["$75"], ["$5"], ["$100"], ["$7"], ["$3"], ["$75"], ["$5"]];
var myFlatArray = myArray.toString().split(',');
myFlatArray;
// ["$6", "$12", "$25", "$25", "$18", "$22", "$10", "$0", "$15", "$3", "$75", "$5", "$100", "$7", "$3", "$75", "$5"]
This should work on any depth of nested arrays containing only strings and numbers(integers and floating points) with the caveat that numbers will be converted to strings in the process. This can be solved with a little mapping:
var myArray =[[[1,2],[3,4]],[[5,6],[7,8]],[[9,0]]];
var myFlatArray = myArray.toString().split(',').map(function(e) { return parseInt(e); });
myFlatArray;
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
To flatten a two-dimensional array in one line:
[[1, 2], [3, 4, 5]].reduce(Function.prototype.apply.bind(Array.prototype.concat))
// => [ 1, 2, 3, 4, 5 ]
[[1, 2], [3, 4, 5], [6, [[7]]]].Recursive version that works on all datatypes
/*jshint esversion: 6 */
// nested array for testing
let nestedArray = ["firstlevel", 32, "alsofirst", ["secondlevel", 456,"thirdlevel", ["theinnerinner", 345, {firstName: "Donald", lastName: "Duck"}, "lastinner"]]];
// wrapper function to protect inner variable tempArray from global scope;
function flattenArray(arr) {
let tempArray = [];
function flatten(arr) {
arr.forEach(function(element) {
Array.isArray(element) ? flatten(element) : tempArray.push(element); // ternary check that calls flatten() again if element is an array, hereby making flatten() recursive.
});
}
// calling the inner flatten function, and then returning the temporary array
flatten(arr);
return tempArray;
}
// example usage:
let flatArray = flattenArray(nestedArray);
The following code will flatten deeply nested arrays:
/**
* [Function to flatten deeply nested array]
* @param {[type]} arr [The array to be flattened]
* @param {[type]} flattenedArr [The flattened array]
* @return {[type]} [The flattened array]
*/
function flattenDeepArray(arr, flattenedArr) {
let length = arr.length;
for(let i = 0; i < length; i++) {
if(Array.isArray(arr[i])) {
flattenDeepArray(arr[i], flattenedArr);
} else {
flattenedArr.push(arr[i]);
}
}
return flattenedArr;
}
let arr = [1, 2, [3, 4, 5], [6, 7]];
console.log(arr, '=>', flattenDeepArray(arr, [])); // [ 1, 2, [ 3, 4, 5 ], [ 6, 7 ] ] '=>' [ 1, 2, 3, 4, 5, 6, 7 ]
arr = [1, 2, [3, 4], [5, 6, [7, 8, [9, 10]]]];
console.log(arr, '=>', flattenDeepArray(arr, [])); // [ 1, 2, [ 3, 4 ], [ 5, 6, [ 7, 8, [Object] ] ] ] '=>' [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
You can use Ramda JS flatten
var arr = [[1,2], [3], [4,5]];
var flattenedArray = R.flatten(arr);
console.log(flattenedArray)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>
/**
* flatten an array first level
* @method flatten
* @param array {Array}
* @return {Array} flatten array
*/
function flatten(array) {
return array.reduce((acc, current) => acc.concat(current), []);
}
/**
* flatten an array recursively
* @method flattenDeep
* @param array {Array}
* @return {Array} flatten array
*/
function flattenDeep(array) {
return array.reduce((acc, current) => {
return Array.isArray(current) ? acc.concat(flattenDeep(current)) : acc.concat([current]);
}, []);
}
/**
* flatten an array recursively limited by depth
* @method flattenDepth
* @param array {Array}
* @return {Array} flatten array
*/
function flattenDepth(array, depth) {
if (depth === 0) {
return array;
}
return array.reduce((acc, current) => {
return Array.isArray(current) ? acc.concat(flattenDepth(current, --depth)) : acc.concat([current]);
}, []);
}
return Array.isArray(current) ? acc.concat(current) : acc.concat([current]);? Why even check for if the item is also an array, if it's just one level :)[1,2].concat(3) is same as [1,2].concat([3])
reduce+concatare O((N^2)/2) where as a accepted answer (just one call toconcat) 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 singleconcat. For thereducefolks 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.array.flat(Infinity)whereInfinityis the maximum depth to flatten.