数组对象去重

2020-08-05  本文已影响0人  黄黄黄大帅
数组去重

1.Set

const array = [' ', 1,  2, ' ',' ', 3];
[...new Set(array)];

set是ES6中引入的新的数据类型。set只允许存储不重复的值,所以当你放入一个数组,它会自动去掉重复的值。

const array = [' ', 1,  2, ' ',' ', 3];
​
// Step 1
const uniqueSet = new Set(array);
// Set { ' ', 1, 2, 3 }
​
// Step 2
const backToArray = [...uniqueSet];
// [' ', 1, 2, 3]

当然,你也可以使用Array.form来将set转回数组

const array = [' ', 1,  2, ' ',' ', 3];
​
Array.from(new Set(array));
​
// [' ', 1, 2, 3]

2.map

function unique(arr){
    const map = new Map()
    return arr.filter((item) => !map.has(item) && map.set(item, true))
}
function unique(arr) {
  let hashMap = new Map();
  let result = new Array();  // 数组用于返回结果
  for (let i = 0,len=arr.length; i < len; i++) {
    if(!hashMap.has(arr[i])) { // 判断 hashMap 中是否已有该 key 值
         hashMap.set(arr[i], true);  
         result.push(arr[i]);
    }
  } 
  return result;
}

3.Filter

array.filter((item, index) => array.indexOf(item) === index)

先说说这两个方法:indexOf()和filter()
-indexOf
从一个数组中返回给定元素第一次出现的索引

const array = [' ', 1,  2, ' ',' ', 3];
​
array.indexOf(' '); // 0
array.indexOf(1); // 1
array.indexOf(2); // 2
array.indexOf(3); // 5

-filter
filter()方法通过给定的条件(一个函数)来返回一个新的数组。换句话说,如果轮到的这个元素进入了条件函数后结果为true,那么它将被加入到过滤后的新数组中,反之则不会加入到结果数组中。

const array = [' ', 1,  2, ' ',' ', 3]
​
array.filter((item, index) => {
  console.log(
    // a. Item
    item,
    // b. Index
    index,
    // c. indexOf
    array.indexOf(item),
    // d. Condition
    array.indexOf(item) === index,
  );
​
  return array.indexOf(item) === index
});

重复的元素就是那些index和indexOf不同的元素,说的再简单点,就是所有重复元素只取第一次出现的那个,后来出现的丢弃。

那如何得到重复的元素呢?将上面的条件反一反就可以啦

const array = [' ', 1,  2, ' ',' ', 3];
​
array.filter((item, index) => array.indexOf(item) !== index);
​
// [' ',' ']

4.Reduce
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。

let arr = [1, 2, 2, 4, null, null].reduce((total, current) => {
    return total.includes(current) ? total: total.concat(current);
}, []);

reduce用来检查最终结果是否已经包含这个item。如果不包含,那么将它放入最终结果,如果已经包含,则丢弃(或者说跳过)这个item。

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
/*total 必需。初始值, 或者计算结束后的返回值。
/currentValue   必需。当前元素
currentIndex    可选。当前元素的索引
arr 可选。当前正在被循环的当前数组。可能不断变化。
initialValue    可选。传递给函数的初始值*/

5.利用for嵌套for,然后splice去重

function unique(arr){            
        for(var i=0; i<arr.length; i++){
            for(var j=i+1; j<arr.length; j++){
                if(arr[i]==arr[j]){         //第一个等同于第二个,splice方法删除第二个
                    arr.splice(j,1);
                    j--;
                }
            }
        }
return arr;
}
对象去重

1.利用对象访问属性的方法,判断对象中是否存在key

 function  unique(arr, ukey) {
      let result = {}
      let obj = {}
      for (let i = 0, len = arr.length; i < len; i++) {
        if (!obj[arr[i][ukey]]) {
          result.push(arr[i])
          obj[arr[i][ukey]] = true
        }
      }
      return result
 }

2.reduce

 let array=[{id:'1',result:'xx'},{id:'3',result:'ll'},{id:'1',result:'xx'}]
function unique(array,u_key){
 let hash={}
 let newObj=array.reduce((total, currentValue) => {
        hash[currentValue[u_key]] ? '' : (hash[currentValue[u_key]] = true && total.push(currentValue))
        return total
      }, [])
}

3.map

function unique(arr,u_key) {
  let map = new Map()
  arr.forEach((item,index)=>{
    if (!map.has(item[u_key])){
      map.set(item[u_key],item)
    }
  })
  return [...map.values()]
}
上一篇下一篇

猜你喜欢

热点阅读