Home >Web Front-end >JS Tutorial >Summary of JavaScript method examples for removing duplicate elements from an array

Summary of JavaScript method examples for removing duplicate elements from an array

伊谢尔伦
伊谢尔伦Original
2017-07-22 14:07:291413browse

Array deduplication;

The Array type does not provide a deduplication method. If you want to remove duplicate elements from the array, you have to find a way yourself:

Method one: Use the indexOf method;


var aa=[1,3,5,4,3,3,1,4]
function arr(arr) {
  var result=[]
  for(var i=0; i<arr.length; i++){
    if(result.indexOf(arr[i])==-1){
      result.push(arr[i])
    }
  }
  console.log(result)
}      
arr(aa)

Method two:


function unique(arr) {
  var result = [], isRepeated;
  for (var i = 0, len = arr.length; i < len; i++) {
    isRepeated = false;
    for (var j = 0, len = result.length; j < len; j++) {
      if (arr[i] == result[j]) {  
        isRepeated = true;
        break;
      }
    }
    if (!isRepeated) {
      result.push(arr[i]);
    }
  }
  return result;
}

The general idea is to move the array elements one by one Go to another array and check whether the element is duplicated during the transfer. If so, discard it directly. As can be seen from nested loops, this method is extremely inefficient. We can use a hashtable structure to record existing elements, so that we can avoid inner loops. It just so happens that implementing hashtable in Javascript is extremely simple. The improvements are as follows:


function unique(arr) {
  var result = [], hash = {};
  for (var i = 0, elem; (elem = arr[i]) != null; i++) {
    if (!hash[elem]) {
      result.push(elem);
      hash[elem] = true;
    }
  }
  return result;
}

The above is the detailed content of Summary of JavaScript method examples for removing duplicate elements from an array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn