Answers for "flatten nested array javascript"

21

javascript array flatten

// flat(depth), 
// depth is optional: how deep a nested array structure 
//		should be flattened.
//		default value of depth is 1 

const arr1 = [1, 2, [3, 4]];
arr1.flat(); 
// [1, 2, 3, 4]

const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

const arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]

const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Posted by: Guest on March-16-2020
1

flatten nested array javascript

// using recursion, .reduce() and .concat() methods
// works with arrays of any depth

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

/*
	Output: [ 1, 2, 3, 4, 5 ]
*/
Posted by: Guest on May-30-2020
1

flatten an array javascript

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

console.log(merged);
Posted by: Guest on April-12-2020
2

Javascript flatten array of arrays

var multiDimensionArray = [["a"],["b","c"],["d"]]; //array of arrays
var flatArray = Array.prototype.concat.apply([], multiDimensionArray); //flatten array of arrays
console.log(flatArray); // [ "a","b","c","d"];
Posted by: Guest on July-25-2019
1

flatten nested array javascript

const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
Posted by: Guest on November-02-2020
2

array flatten

const arr = [1, 2, [3, 4]];

// To flat single level array
arr.flat();
// is equivalent to
arr.reduce((acc, val) => acc.concat(val), []);
// [1, 2, 3, 4]

// or with decomposition syntax
const flattened = arr => [].concat(...arr);
Posted by: Guest on June-01-2020

Code answers related to "Javascript"

Browse Popular Code Answers by Language