Given an array in Javascript, Flatten its elements so it becomes one-dimension. For example, flatten([1, [[2], 3, 4], 5]) becomes [1, 2, 3, 4, 5].
In ES6, you can use the array.Prototype.flatten method which flattens the elements of an array. The parameter specifies the depth the flattening process goes to – default is two. You can pass in Infinity to flattens the array no matter how deep the elements are.
1 2 3 4 5 6 | const a = [1, 2, [3, 4, 5, [6, 7]], 8]; undefined a.flat(Infinity) (8) [1, 2, 3, 4, 5, 6, 7, 8] a.flat() (7) [1, 2, 3, 4, 5, Array(2), 8] |
const a = [1, 2, [3, 4, 5, [6, 7]], 8]; undefined a.flat(Infinity) (8) [1, 2, 3, 4, 5, 6, 7, 8] a.flat() (7) [1, 2, 3, 4, 5, Array(2), 8]
Before ES6, you can write a flatten method like this:
1 2 3 4 5 6 7 8 9 10 11 | const flatten = (arr) => { let result = []; arr.forEach(function (v) { if (Array.isArray(v)) { result = result.concat(flatten(v)); } else { result.push(v); } }); return result; } |
const flatten = (arr) => { let result = []; arr.forEach(function (v) { if (Array.isArray(v)) { result = result.concat(flatten(v)); } else { result.push(v); } }); return result; }
The idea is to iterate the array using forEach and if the element itself is an array (Array.isArray) – we recursively flatten and concat to the result array. Otherwise, the element is simply pushed to result array.
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading...
261 wordsloading...
Last Post: How to Implement a Safe Data Get Function in Javascript?
Next Post: The Javascript Function to Check Any Two Sets Are the Same