flat array
已知如下数组:
var arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10];
编写一个程序将数组扁平化去并除其中重复部分数据,最终得到一个升序且不重复的数组
simple
arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10];
(4) [Array(3), Array(4), Array(5), 10]
newArr = arr.flat(Infinity);
(17) [1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12, 13, 14, 10]
newArr = [...new Set(newArr)];
(14) [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 10]
newArr.sort((a, b) => a - b > 0 ? 1 : -1);
(14) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10];
(4) [Array(3), Array(4), Array(5), 10]
arrFlat = (arr = []) => {
let result = [];
arr.forEach((item, i) => {
if(Array.isArray(item)) {
const temp = arrFlat(item)
result = result.concat(temp);
} else {
result.push(item);
}
});
return result;
}
newArr = arrFlat(arr);
(17) [1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12, 13, 14, 10]
newArr = [...new Set(newArr)];
(14) [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 10]
newArr.sort((a, b) => a - b > 0 ? 1 : -1);
(14) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]