日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

數組去重并找到所有重復的項的索引位置

作者:Mr.一 更新時間: 2022-04-22 編程語言
例如此例子。找到該數組里面對象擁有相同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); //?[{…}, {…}, {…}, {…}]   //這里得到重復的具體的所有項值

原文鏈接:https://blog.csdn.net/weixin_46016926/article/details/118739163

欄目分類
最近更新