數組去重的5種方法,兩個數組去重合併

1、循環遍歷去重

定義一個空數組,循環原數組,檢測每一項是否在將新數組中,如果不在就將該項存儲到新數組中。再循環新數組,將每一項還原為原來的類型,存入新的數組中,所得的新數組就是去重後得到數組。

const arr = [{ a: 1, b: 1 },true,0,1,null,undefined,true,false,1,{ a: 1, b: 1 },undefined,null,false,0],
           res1 = [];
arr.forEach((item) => {
      const str = JSON.stringify(item) + "";
      if (res1.indexOf(str) === -1) {
           res1.push(str);
       }
});
const res2 = res1.map((item) => {
         return item === undefined + "" ? undefined : JSON.parse(item);
});
console.log(res2); //  [{a: 1, b: 1},true,0,1,null,undefined,false]

2、利用對象的屬性名的不重複型

定義一個新的空對象,循環原數組,將每一項轉換為字元串的值作為對象的屬性名,每一項作為對象的屬性值。然後遍歷對象,將對象屬性名對應的屬性值都放入一個新建的數組中。所得的新數組就是去重後得到數組。

const arr = [{ a: 1, b: 1 },true,0,1,null,undefined,true,false,1,{ a: 1, b: 1 },undefined,null,false,0],
      obj={};
arr.forEach((item) => {
      const str = JSON.stringify(item) + "";
      obj[str]=item
});
const res = [];
Object.keys(obj).forEach((item) => {
        res.push(obj[item]);
});
console.log(res); //  [{a: 1, b: 1},true,0,1,null,undefined,false]

3、利用ES6中Set的特性

循環數組,將數組中的每一項轉換為字元串,存入新的數組中。利用Set集合元素的唯一性去重得到set集合,再將得到的set集合轉換為新的數組。再循環新數組將每一項還原為原來的類型,存入新的數組中,所得的新數組就是去重後得到數組。

const arr = [{ a: 1, b: 1 },true,0,1,null,undefined,true,false,1,{ a: 1, b: 1 },undefined,null,false,0],
           res1 = [];
arr.forEach((item) => {
      const str = JSON.stringify(item) + "";
      res1.push(str);
});
const set = new Set(res1);
const res2 = Array.from(set);
const res3 = res2.map((item) => {
         return item === undefined + "" ? undefined : JSON.parse(item);
});
console.log(res3); //  [{a: 1, b: 1},true,0,1,null,undefined,false]

原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/229853.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
投稿專員的頭像投稿專員
上一篇 2024-12-10 13:16
下一篇 2024-12-10 13:16

相關推薦

發表回復

登錄後才能評論