JavaScript 数组扁平化,去重,排序
var arr = [
[2, 3, 4, 5, 6, 7, [1, 2, 3, 4, 6, 7]],
[2, 4, 5, 6, 7, 8, 9, 0, [4, 4, [3, 4, 5, 6], 6, 7, 2]],
[2, 3, 4, 5, 6, ], 1, 2, 3, 4, 5, 6, 7
];
//扁平化
function flatten(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(flatten(item))
} else {
fArr.push(item);
}
}
return fArr;
function _isArr() {
return {}.toString.call(item) === '[object Array]';
}
}
Array.prototype.flatten = function() {
var _arr = this;
toStr = {}.toString;
if (toStr.call(_arr) !== '[object Array]') {
throw new Error('只有数组才能调用flatten方法');
}
var fArr = [];
_arr.forEach(function(item) {
toStr.call(item) === '[object Array]' ?
fArr = fArr.concat(item.flatten()) :
fArr.push(item);
});
return fArr;
}
Array.prototype.flatten1 = function() {
var _arr = this;
toStr = {}.toString;
if (toStr.call(_arr) !== '[object Array]') {
throw new Error('只有数组才能调用flatten方法');
}
var fArr = [];
return _arr.reduce(function(prev, item) {
return prev.concat(toStr.call(item) === '[object Array]' ?
item.flatten() :
item);
}, []);
}
const flatten1 = arr => arr.reduce((prev, item) => pre.concat({}.toString().call(item) === '[object Array]' ?
flatten(item) : item), []);
console.log(Array.from(new Set(arr.flat(Infinity))).sort((a,b)=> a-b));