要求:编写一个程序将数组扁平化并将扁平化后的数组去重,最终得到一个升序且不重复的一维数组。
var arr = [[1, 2, 3], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14]]]], 10];
1. 简洁的实现方式:Array.from(new Set(arr.flat(Infinity))).sort((a, b) => a - b)
- arr.flat(depth):
- flat() 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。
- 其中,depth指定要提取嵌套数组的结构深度,默认值为1。但使用 Infinity 作为深度,展开任意深度的嵌套数组
- 扁平化:将多维数组转化为一维数组的程序叫扁平化程序
var arr = [[1, 2, 3], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14]]]], 10];
console.log(Array.from(new Set(arr.flat(Infinity))).sort((a, b) => a - b));
2. 数据扁平化-递归的方式
function flatten(arr) {
var _arr = arr || [],
fArr = [],
arrLen = _arr.length,
item;
for (var i = 0; i < arrLen; i++) {
item = _arr[i];
if (_isArr(item)) {
fArr = fArr.concat(flatten(item));
} else {
fArr.push(item);
}
}
return fArr;
function _isArr(item) {
return {}.toString.call(item) === '[object Array]';
}
}
console.log(flatten(arr).sort(function (a, b) {
return a - b;
}))
3. 数据扁平化-在原型上封装flatten()方法--1.forEach()
Array.prototype.flatten1 = function () {
var _arr = this,
toStr = {}.toString,
fArr = [];
if (toStr.call(_arr) !== '[object Array]') {
throw new Error('只有数组可以调用flatten方法');
}
_arr.forEach(function (item) {
toStr.call(item) === '[object Array]'
? fArr = fArr.concat(item.flatten1())
: fArr.push(item);
});
return fArr;
}
console.log(arr.flatten1());
4. 数据扁平化-在原型上封装flatten()方法--2.reduce()
Array.prototype.flatten2 = function () {
var _arr = this,
toStr = {}.toString;
if (toStr.call(_arr) !== '[object Array]') {
throw new Error('只有数组可以调用flatten方法');
}
return _arr.reduce(function (prev, item) {
return prev.concat(toStr.call(item) === '[object Array]'
? item.flatten2()
: item
);
}, [])
}
console.log(arr.flatten2());
5. 数据扁平化- es6 -reduce()
const flatten3 = (array) => {
return array.reduce((prev, item) => {
return prev.concat({}.toString.call(item) === '[object Array]'
? flatten3(item)
: item
);
}, [])
}
console.log('flatten3', flatten3(arr));
const flatten4 = array =>
array.reduce((prev, item) =>
prev.concat({}.toString.call(item) === '[object Array]'
? flatten4(item)
: item
);
, [])
console.log('flatten4', flatten4(arr));