Array de-weighting is encountered very, very often in front end interviews. There are many ways to solve this problem, and today I’m going to introduce you to three of the most common and useful array de-duplication methods.

Now let’s de-redo this array.

var arr  = [1.1.'true'.'true'.true.true.15.15.false.false.undefined.undefined.null.null.NaN.NaN.'NaN'.0.0.'a'.'a', {}, {}];Copy the code

Set

The Set object is the most useful tool for de-weighting, no one, because of its unique characteristics, very suitable for de-weighting requirements.

A Set object is a collection of values, and you can iterate over its elements in the order in which they are inserted. Elements in a Set occur only once, that is, the elements in a Set are unique.

function arr_unique1(arr){
    return  [...new Set(arr)];
}
Copy the code

The Set + extension operator does the most elegant array de-duplication. This is probably the easiest array de-duplication.

But it also relies too heavily on the use of JavaScript built-in tools, which can only prove your familiarity with new JavaScript features, but not your logic.

Map

A Map object is also a Set of key-value pairs similar to a Set object. Although it does not have the unique properties of a Set, it does provide a number of methods to perform deduplication.

function arr_unique2(arr) {
    let map = new Map(a);let array = new Array(a);// The array is used to return the result
    for (let i = 0; i < arr.length; i++) {
      if(map.has(arr[i])) {  // If there is a key value
        map.set(arr[i], true);
      } else {
        map.set(arr[i], false);   // If there is no key valuearray.push(arr[i]); }}console.log('Map:');
    console.log(map);
    console.log(array);
    return array;
  }
Copy the code

Give home heavy

In addition to using sets and maps, one of the most primitive methods is recursive repetition, which may seem cumbersome, but it’s a great test of your coding skills.

function arr_unique3(arr) {
    var array= arr;
    var len = array.length;
    array.sort(function(a,b){   // It is more convenient to remove the weight after sorting
    return a - b;
   })
   console.log('the recursive',array);
   
function loop(index){
       if(index >= 1) {if(array[index] === array[index-1]){
               array.splice(index,1);
           }
           loop(index - 1);    // loop recursively, then the array is deduplicated
       }
   }
   loop(len-1);
   return array;
}
Copy the code

Before looping through, we first sort the original array using JavaScript’s built-in sort method. This way, the same values in the array are next to each other, making it easier to undo.

There are thousands of ways to do this, and mastering these three methods is enough to get you through most interviews!