js 数组去重和对象数组去重

数组去重:

  1. Set 结构不会添加重复的值。Array.from把 Set 结构转换为数组
  2. map.has(property)判断属性是否存在 ,map的键不会转换为字符串
  3. Array.includes(value) 判断值是否存在于数组中
  4. 遍历两次,使用===全等运算符判断是否相等
  5. 使用 filter 过滤数组,hasOwnProperty 判断对象是否存在某属性,将数据类型和数据作为对象的属性,如果存在相同的就返回false,表示过滤。
let originalArray = [1,2,3,4,5,3,2,4,1];

// 方式1 Set
const result = Array.from(new Set(originalArray));
console.log(result); // -> [1, 2, 3, 4, 5]

// 方式2
const result = [];
const map = new Map();
for (let v of originalArray) {
    if (!map.has(v)) {
        map.set(v, true);
        result.push(v);
    }
}
console.log(result); // -> [1, 2, 3, 4, 5]

// 方式3
const result = [];
for (let v of originalArray) {
    if (!result.includes(v)) {
        result.push(v);
    }
}
console.log(result); // -> [1, 2, 3, 4, 5]

// 方式4
for (let i = 0; i < originalArray.length; i++) {
    for (let j = i + 1; j < originalArray.length; j++) {
        if (originalArray[i] === originalArray[j]) {
            originalArray.splice(j, 1);
            j--;
        }
    }
}
console.log(originalArray); // -> [1, 2, 3, 4, 5]

// 方式5
const obj = {};
const result = originalArray.filter(item => obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item] = true));
console.log(result); // -> [1, 2, 3, 4, 5]

对象数组去重:

reduce 用法
语法:array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

const responseList = [
	  { id: 1, a: 1 },
	  { id: 2, a: 2 },
	  { id: 3, a: 3 },
	  { id: 1, a: 4 },
];
const result = responseList.reduce((acc, cur) => {
    //map用于返回符合表达式的数据
    const ids = acc.map(item => item.id);
    // ...运算符用于将数组拆成,分隔的字符串
    return ids.includes(cur.id) ? acc : [...acc, cur];
}, []);
console.log(result); // -> [ { id: 1, a: 1}, {id: 2, a: 2}, {id: 3, a: 3} ]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值