Example 1: javascript array flatten
const arr1 = [1, 2, [3, 4]];
arr1.flat();
const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
const arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
Example 2: flatten nested array javascript
function flatten(arr)
{
return arr.reduce((acc, cur) => acc.concat(Array.isArray(cur) ? flatten(cur) : cur), []);
};
const arr = [[1,2],[3,[4,[5]]]];
const flattened = flatten(arr);
console.log(flattened);
Example 3: array flatten
const arr = [1, 2, [3, 4]];
arr.flat();
arr.reduce((acc, val) => acc.concat(val), []);
const flattened = arr => [].concat(...arr);
Example 4: flatten an array javascript
var arrays = [
["$6"],
["$12"],
["$25"],
["$25"],
["$18"],
["$22"],
["$10"]
];
var merged = [].concat.apply([], arrays);
console.log(merged);
Example 5: flatten an array in javascript
function falltenArray(arr) {
let result = [...arr];
let flattened = false;
let counter = 0;
while (flattened === false){
if (Array.isArray(result[counter])){
result.splice(counter, 1, ...result[counter]);
counter = 0;
} else {
counter += 1;
}
if (counter === result.length){
flattened = true;
}
}
return result;
}
Example 6: Javascript flatten array of arrays
var multiDimensionArray = [["a"],["b","c"],["d"]];
var flatArray = Array.prototype.concat.apply([], multiDimensionArray);
console.log(flatArray);