Array de-duplication, object array de-duplication

1. Ordinary array, use ES6 Set to remove duplicates

  function Deduplication(arr){
    
    
      return Array.from(new Set(arr));
  }
或者
  function Deduplication(arr){
    
    
      return [...new Set(arr)];
  }
  let arrs = ["aaa", "aaa", "san", "www", "san"];
  console.log(Deduplication(arr)) // ["aaa", "san", "www"]

Reference: GitBook

Two, the array object to remove the duplicate, according to the name to remove the duplicate

  1. Define an object obj, used to install the data in the array object, the key is name, the value is boolean value, and a result is defined to install the result
  2. When traversing the data arrs, name appears for the first time, push the data into the result.
//根据name,给数组对象去重
function  Deduplication(arrs) {
    
    
      var obj = {
    
    };
      let result = [];
      arrs.forEach(val => {
    
    
        if (!obj[val.name]) {
    
     // 说明 name第一次出现,
          obj[val.name] = true; // obj的键为数据name,值为true,代表该name出现了,此次就不会进if,故不会将出现过的name再次push到result中了。
          result.push(val);
        }
      });
      return result;
}

let arrs = [
                {
    
     name: "aaa" },
                {
    
     name: "aaa" },
                {
    
     name: "san" },
                {
    
     name: "www" },
                {
    
     name: "san" }
           ];
           
console.log(Deduplication(arrs)) // [{name: "aaa"}, {name: "san"}, {name: "www"}]

Guess you like

Origin blog.csdn.net/ddx2019/article/details/108759081