js中常用去重方法
ES6 提供了 Set 类型,它可以自动去重
const arr = [1, 2, 2, 3, 3, 4];
const newArr = Array.from(new Set(arr));
console.log(newArr ); // [1, 2, 3, 4]
const arr = [1, 2, 2, 3, 3, 4];
const newArr = arr.filter((item, index) => {
return arr.indexOf(item) === index;
});
console.log(newArr); // [1, 2, 3, 4]
const arr = [1, 2, 2, 3, 3, 4];
const newArr= arr.reduce((acc, cur) => {
if (!acc.includes(cur)) {
acc.push(cur);
}
return acc;
}, []);
console.log(newArr); // [1, 2, 3, 4]
const arr = [1, 2, 2, 3, 3, 4];
const obj = {};
//f方式1
//const newArr= arr.filter((item) => {
// return obj.hasOwnProperty(item) ? false : (obj[item] = true);
//});
//方式2
arr.forEach(item=>obj[item] = item)
const newArr= Object.keys(obj) //Object.values(obj)
console.log(newArr); // [1, 2, 3, 4]
onst arr = [1, 2, 2, 3, 3, 4];
const map = new Map();
const newArr= arr.filter((item) => !map.has(item) && map.set(item, true));
console.log(newArr); // [1, 2, 3, 4]
const arr = [1, 2, 2, 3, 3, 4];
const newArr= arr.filter((item, index) => {
return arr.indexOf(item) === index;
});
console.log(newArr);
const arr = [1, 2, 2, 3, 3, 4];
const newArr= [...new Set(arr)];
console.log(newArr); // [1, 2, 3, 4]