js查找数组对象中有相同属性和值的数据项

// 例如此例子。找到该数组里面对象拥有相同name的对象索引,以及值      
      const objs = [
        { name: "1", age: 12 },
        { name: "2", age: 12 },
        { name: "3", age: 12 },
        { name: "1", age: 12 },
        { name: "1", age: 12 },
        { name: "7", age: 12 },
        { name: "1", age: 12 },
      ];
      const arr = [];
      objs.map((s) => {   // 把要比较的数据单独抽离出来。方便看
        arr.push(s.name);
      });
      const res = [];
      arr.map((i, index) => {     // 这里是核心,通过双层循环。比较有没有重复的项
        arr.map((p, ind) => {
          if (p === i && ind !== index) {  // 找到重复的项,并排除掉自身的索引
            res.push(ind);
          }
        });
      });
      let result = Array.from(new Set(res));   // 数组去重方法
      console.log(result); //[3, 4, 6, 0]     // 这里就得到重复项的索引位置
      const finallys = result.map((l) => {
        return objs[l];
      });
      console.log(finallys); // [{…}, {…}, {…}, {…}]   // 这里得到重复的具体的所有项值
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值