一、数组扁平化是指将一个多维数组变为一个一维数组
const arr = [1, [2, [3, [4, 5]]], 6];
// => [1, 2, 3, 4, 5, 6]
//-------------------------------------------------------------------------------------
// 方法1
const array = arr.flat(Infinity)
// 方法2
const res2 = JSON.stringify(arr).replace(/\[|\]/g, '').split(',');
二、数组去重
const arr = [1, 1, '1', 17, true, true, false, false, 'true', 'a', {}, {}];
// => [1, '1', 17, true, false, 'true', 'a', {}, {}]
//-------------------------------------------------------------------------------------
//方法1(set)
const res1 = Array.from(new Set(arr));
//方法2 (filter)
const unique4 = arr => {
return arr.filter((item, index) => {
return arr.indexOf(item) === index;
});
}
//方法3 (Map)
const unique5 = arr => {
const map = new Map();
const res = [];
for (let i = 0; i < arr.length; i++) {
if (!map.has(arr[i])) {
map.set(arr[i], true)
res.push(arr[i]);
}
}
return res;
}