current position:Home>Front end interview question - Summary of array de duplication method

Front end interview question - Summary of array de duplication method

2021-08-26 17:39:59 stan

Array weight removal

1. Set

Array.from(new Set(arr))

/*  perhaps  */
[...new Set(arr)]

2. Map

3. Array.prototype.indexOf Method

4. Array.prototype.includes Method

5. Array.prototype.filter Method

function unique(arr) {
  return arr.filter(function(item, index, arr) {
    //  If the first index of the current element in the original array is equal to the current index , Returns the current element 
    return arr.indexOf(item, 0) === index;
  });
}

6. Array.prototype.reduce Method + Array.prototype.includes Method

function unique(arr){
  return arr.reduce((prev, cur) => prev.includes(cur) ? prev : [...prev, cur], []);
}

7. Array.prototype.sort Method

copyright notice
author[stan],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210826173957133g.html

Random recommended