数组扁平化,去重,排序
var startArr = [
[1, 1, 2],
[3, 2, 5, 4],
[4, 5, 4, 1],
[1, 3, 8, 9, [44, 41, 15, [14, 7, 9, [25]]], 18],
];
1. es5
1.1 for
function flattern(arr) {
var _arr = arr || [],
fArr = [],
len = _arr.length,
item;
for (var i = 0; i < len; i++) {
item = _arr[i];
if (_isArr(item)) {
fArr = fArr.concat(flattern(item));
} else {
fArr.push(item);
}
}
return fArr;
function _isArr(item) {
return {}.toString.call(item) === '[object Array]';
}
}
1.2 map
function flatternMap(arr) {
var res = [];
if (!Array.isArray(arr)) {
throw new Error('no Array');
}
arr.map(item => {
if (Array.isArray(item)) {
res = res.concat(flatternMap(item));
} else {
res.push(item);
}
});
return res;
}
1.3 reduce
function flatterReduce(arr) {
var res = [];
if (!Array.isArray(arr)) {
throw new Error('no Array');
}
return arr.reduce((prev, item) => {
return prev.concat(Array.isArray(item) ? flatterReduce(item) : item);
}, []);
}
2. es6
2.1 reduce
const flatterReduceEs6 = arr =>
arr.reduce((prev, item) => {
return prev.concat(Array.isArray(item) ? flatterReduceEs6(item) : item);
}, []);
2.2 flat
arr.flat(Infinity);
Array.from(new Set(startArr.flat(Infinity).sort((a, b) => a - b)));