1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
function flatten1 (array) {
return array.reduce((pre, item) => { if (Array.isArray(item) && item.some((cItem => Array.isArray(cItem)))) { return pre.concat(flatten1(item)) } else { return pre.concat(item) } }, []) }
function flatten2 (arr) { while (arr.some(item => Array.isArray(item))) { arr = [].concat(...arr) } return arr }
var arr = [ [1, 2, 2], [3, 4, 5, 5], [5, 6, 7, 8, 9], [11, 12, [12, 12, [13]]], 10, ]; Array.prototype.flat = function () { const result = this.map((item) => { if (Array.isArray(item)) { return item.flat(); } return [item]; }); return [].concat(...result); }; Array.prototype.unique = function () { return [...new Set(this)]; }; const sortFn = (a, b) => { return a - b; }; const a = arr.flat().unique().sort(sortFn); console.log(a);
|