关于校验数组重复那点小事

1.找到数组中重复的元素

function findRepeatNumInArray(arr) {

  let hashMap = new Map();

  let result = new Array();

  for (let i = 0; i < arr.length; i++) {

    hashMap.set(arr[i], hashMap.has(arr[i]))

  }

  // 得到 hashMap 后,对其进行遍历,值为 true,对应的键就是重复的数

  for(let [key, value] of hashMap.entries()) {

    if(value === true) {

      result.push(key);

    }

  }

  return result;

}

let arr = [1, 1, 1, 2, 3, 3, 4, 5, 5, "a", "b", "a"];console.log(findRepeatNumInArray(arr));


2.找到数组中第一个非重复的元素

function findFirstNonRepeat(arr) {

  let hashMap = new Map();

  for (let i = 0; i < arr.length; i++) {

    hashMap.set(arr[i], hashMap.has(arr[i]))

  }

  // 找到第一个值为 false 的,就代表第一个非重复数,return 就好了

  for(let [key, value] of hashMap.entries()) {

    if(value === false) {

      return key;

    }

  }

  return "全部重复";

}

let arr = [1, 1, 1, 2, 3, 3, 4, 5, 5, "a", "b", "a"];

console.log(findFirstNonRepeat(arr));

 

3.过滤数组中重复的元素

 利用Set

let Arr = [1,1]

var res = Array.from(new Set(Arr));

console.log(res); //[1]

 

4.如果有遇到一个数组中存储多个对象,有部分对象的某一个键值是相同的,需要过滤掉重复项的实现方案

const arr =[

  {

    "count": 1095,

    "month": "三月",

  },

  {

    "count": 1106,

    "month": "三月",

  },

  {

    "count": 987,

    "month": "四月",

  },

  {

    "count": 1166,

    "month": "四月",

  },

  {

    "count": 753,

    "month": "五月",

  },

  {

    "count": 891,

    "month": "五月",

  }

];

const res = new Map();

const new2 = arr.filter(item => !res.has(item.month) && res.set(item.month, 1));

console.log(arr.length, new2);

 

 数组合并并去重

const a = [{ id: 1, name: 2 }];

const b = [{ id: 1, name: 3 }];

const c = [...a, ...b];

var arr1 = [

  { id: 1, name: 'car2' },

  { id: 2, name: 'car3' },

];

var arr2 = [

  { id: 1, name: 'acar22' },

  { id: 2, name: 'acar32' },

  { id: 3, name: 'acar3' },

];

const combined = (arr1, arr2, type) =>

  arr2.reduce((acc, cur) => {

    const target = acc.find(e => e[type] === cur[type]);

    // console.log(target);

    if (target) {

      Object.assign(target, cur);

    } else {

      acc.push(cur);

    }

    return acc;

  }, arr1);

console.log(c, '引用类型,所以去重失败');

console.log(combined(arr1, arr2, 'id'), '成功合并并去重');

 

 

 5.将数组中key值重复的元素整合在一起

ObjArr=[ {key:1,value:'apple'}, {key:2,value:'banana'}, {key:1,value:'orange'}, {key:2,value:'peach'} ]

let ArrObj={}

 ObjArr.forEach(function (obj) { let array = ArrObj[obj['key']] || [] array.push(obj) ArrObj[obj['day']] = array })

ArrObj={ 1:[{key:1,value:'apple'},{key:1,value:'orange'}], 2:[{key:2,value:'banana'},{key:2,value:'peach'}] } 

 

 

 

 

posted @ 2021-09-03 18:44  天官赐福·  阅读(102)  评论(0编辑  收藏  举报
返回顶端