Two arrays to heavy JS code

  • 2020-03-30 00:45:02
  • OfStack

The first:

function unique (arr){
  var obj = {},newArr = [];
  for(var i = 0;i < arr.length;i++){
    var value = arr[i];
    if(!obj[value]){
      obj[value] = 1;
      newArr.push(value);
    }
  }
  return newArr;
}

This method stores the values of the array in the object, so it fails to run while the array is in the member of the object (the key of the object is converted to a string).
The second method:

function unique (arr){
  for(var i = 0;i < arr.length;i++){
    for(var j = i+1;j < arr.length;j++){
      if(arr[i] === arr[j]){
        arr.splice(j,1);
        j--}
      }
   }
   return arr;
}

This method is supported even if the incoming array contains objects, note '===', but with nested loops, the performance is worse than the first method.

Related articles: