Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

flatten 2d array javascript

const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());
// expected output: [0, 1, 2, 3, 4]

// Flatten 2 levels deep
const arr2 = [0, 1, 2, [[[3, 4]]]]; 
console.log(arr2.flat(2));
// expected output: [0, 1, 2, [3, 4]]

// Flatten all levels
const arr4 = [2, 2, 5, [5, [5, [6]], 7]];
arr4.flat(Infinity);
// [2, 2, 5, 5, 5, 6, 7];
 
PREVIOUS NEXT
Tagged: #flatten #array #javascript
ADD COMMENT
Topic
Name
4+8 =