js基础:数组函数

复制

1
2
3
const arr = [1, 2, { name: "ipenman" }];
const arr2 = [...arr];
console.log(arr2);

去重

1
2
3
4
const arr = [1, 2, { name: "ipenman" }];
const set = new Set(arr);
const arr2 = Array.from(set); // [...set]
console.log(arr2);

合并(不去重)

1
2
3
4
const arr1 = [1, 2];
const arr2 = [2, 3];
const arr = [...arr1, ...arr2];
console.log(arr);

合并(去重)

1
2
3
const arr = [1, 2, 3, 4, 5];
const arr1 = [2, 2, 6, 7];
const arr2 = Array.from(new Set([...a, ...b])); // [1,2,3,4,5,6,7]

交集

1
2
3
4
5
const arr = [1, 2, 3, 54, 5, 6, 7, 21, 4, 2, 2];
const arr1 = [1, 2, 3, 5, 6, 7, 23, 4, 6, 567, 7, 43];
const arr2 = [...new Set(arr)].filter((item) => arr2.includes(item));

console.log(arr2); // [ 1, 2, 3, 5, 6, 7, 4 ]

去空值

1
2
3
const arr = [1, 0, null, undefined, false, NaN, "fdsf", "", ""];
const arr2 = arr.filter(Boolean);
console.log(arr2); // 1,0,fdsf

多维数组平铺一维数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function fn(arr, num) {
num === undefined && (num = find(arr));
if (num > 0) return arr.reduce((x, y) => x.concat(Array.isArray(y) ? fn(y, num - 1) : y), []);
if (num === 0) return arr;
}
function find(arr, num = 1) {
Array.isArray(arr) && arr.length && arr.forEach((item) => find(item, num++));
return num;
}
const arr2 = [
[1, 2],
[3, 4],
[5, 6],
[7, [8, 9]],
];
console.log(arr2); // [1,2,3,4,5,6,7,8,9]
原创技术分享,您的支持将鼓励我继续创作