1.filter 去重
const list = [1, 2, 3, 4, 1, 2, 3, 4, 5];
// filter 去重
const newList = list.filter((item, index, array) => {
return array.indexOf(item) === index;
});
console.log(newList);
2.new Set 去重
const list = [1, 2, 3, 4, 1, 2, 3, 4, 5];
// new Set 去重
const oneList = [...new Set(list)];
console.log(oneList);
3.reduce+includes 去重
const twoList = list.reduce((array, b) => {
return array.includes(b) ? [...array] : [...array, b];
}, []);
console.log(twoList);
4.reduce+indexOf 去重
const twoList = list.reduce((array, b) => {
const bol = !!~array.indexOf(b);
return bol ? [...array] : [...array, b];
}, []);
console.log(twoList);
5.reduce 去重数组对象
const list = [
{ a: 1, b: 2 },
{ a: 1, b: 2 },
{ a: 1, b: 3 },
];
const twoList = list.reduce((array, b) => {
const bol = !!~JSON.stringify(array).indexOf(JSON.stringify(b));
return bol ? [...array] : [...array, b];
}, []);
console.log(twoList); // [ { a: 1, b: 2 }, { a: 1, b: 3 }]
网友评论