Home > Web Front-end > JS Tutorial > body text

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

伊谢尔伦
Release: 2017-07-22 14:07:29
Original
1381 people have browsed it

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)
Copy after login

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;
}
Copy after login

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;
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template