new Set( ) Applicable scenarios for deduplication of arrays

Project scenario:

There are several objects in an array,

var arr = [
            {name:'王',age:'22'},
            {name:'李',age:'16'},
            {name:'张',age:'55'},
            {name:'郝',age:'45'},
            {name:'赵',age:'33'},
            {name:'王',age:'22'},
          ]

 Now deduplicate the array arr


Problem Description

  First of all, the first thing I think of is the simple and easy-to-write ES5 new Set( ); 

  code show as below: 

var newarr = [...new Set(arr)];
console.log(newarr);
//[
//  {name:'王',age:'22'},
//  {name:'李',age:'16'},
//  {name:'张',age:'55'},
//  {name:'郝',age:'45'},
//  {name:'赵',age:'33'},
//  {name:'王',age:'22'},
//]

It was found that it did not take effect after deduplication


Cause Analysis:

new Set() is only applicable to the basic types in the array, so it cannot be deduplicated 


solution:

1. Use reduce to achieve

      let obj = {};

      newarr = arr.reduce((cur,next) => { //next each item

        obj[next.name] ? "" : obj[next.name] = true && cur.push(next);

        return cur;

      },[]) //Set the default type of cur to an array, and the initial value is an empty array

      console.log(newarr);

Guess you like

Origin blog.csdn.net/weixin_63443983/article/details/128487810