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

Recommended two methods for deduplicating JavaScript arrays_javascript skills

WBOY
Release: 2016-05-16 15:06:36
Original
1426 people have browsed it

1. Array deduplication;

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

Method 1: 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 2:

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

Method 2, The general idea is to transfer the array elements to another array one by one. During the transfer process, check whether the element is duplicated, and 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 two recommended methods for deduplicating JavaScript arrays are all the content shared by the editor. I hope it can give you a reference, and I hope you will support Script Home.

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