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

What are the ways to delete duplicate elements from an array in JS

php中世界最好的语言
Release: 2018-04-13 13:33:02
Original
1631 people have browsed it

This time I will bring you the methods of deleting duplicate elements of arrays in JS, and the precautions of deleting duplicate elements of arrays in JS. The following is a practical case, let's take a look.

Here are 5 methods on how to implement array deduplication in js, and a demo and source code are attached.

1.Traverse the arrayMethod

The simplest way to remove duplicates,

Implementation Idea: Create a new array, traverse the incoming array, and add the value to the new array if it is not in the new array; Note: The method "indexOf" to determine whether the value is in the array is an ECMAScript5 method, which is not available below IE8 Supported, you need to write more code that is compatible with lower version browsers. The source code is as follows:

// 最简单数组去重法
function unique1(array){
 var n = []; //一个新的临时数组
 //遍历当前数组
 for(var i = 0; i < array.length; i++){
  //如果当前数组的第i已经保存进了临时数组,那么跳过,
  //否则把当前项push到临时数组里面
  if (n.indexOf(array[i]) == -1) n.push(array[i]);
 }
 return n;
}
// 判断浏览器是否支持indexOf ,indexOf 为ecmaScript5新方法 IE8以下(包括IE8, IE8只支持部分ecma5)不支持
if (!Array.prototype.indexOf){
 // 新增indexOf方法
 Array.prototype.indexOf = function(item){
  var result = -1, a_item = null;
  if (this.length == 0){
   return result;
  }
  for(var i = 0, len = this.length; i < len; i++){
   a_item = this[i];
   if (a_item === item){
    result = i;
    break;
   } 
  }
  return result;
 }
}
Copy after login

2. Object key-value pairing method

This method executes faster than any other method, but it takes up more memory;

Implementation idea: Create a new js object and a new array. When traversing the incoming array, determine whether the value is the key of the js object. If not, add the key to the object and put it into the new array. be careful: When determining whether it is a js object key, "toString()" will be automatically executed on the incoming key. Different keys may be mistaken for the same; for example: a[1], a["1"] . To solve the above problem, you still have to call "indexOf".

// 速度最快, 占空间最多(空间换时间)
function unique2(array){
 var n = {}, r = [], len = array.length, val, type;
  for (var i = 0; i < array.length; i++) {
    val = array[i];
    type = typeof val;
    if (!n[val]) {
      n[val] = [type];
      r.push(val);
    } else if (n[val].indexOf(type) < 0) {
      n[val].push(type);
      r.push(val);
    }
  }
  return r;
}
Copy after login

3. Array subscript judgment method

You still have to call "indexOf", the performance is similar to method 1,

Implementation Idea: If the first occurrence of the i-th item in the current array is not i, it means that the i-th item is repeated and ignored. Otherwise, store the result array.

function unique3(array){
 var n = [array[0]]; //结果数组
 //从第二项开始遍历
 for(var i = 1; i < array.length; i++) {
  //如果当前数组的第i项在当前数组中第一次出现的位置不是i,
  //那么表示第i项是重复的,忽略掉。否则存入结果数组
  if (array.indexOf(array[i]) == i) n.push(array[i]);
 }
 return n;
}
Copy after login

4. Adjacent removal method after sorting

Although the sorting results of the "sort" method of native arrays are not very reliable, this shortcoming has no impact in deduplication that does not pay attention to order.

Implementation idea: Sort the incoming array. After sorting, the same values ​​are adjacent, and then when traversing, only add values ​​that are not duplicates of the previous value to the new array.

// 将相同的值相邻,然后遍历去除重复值
function unique4(array){
 array.sort(); 
 var re=[array[0]];
 for(var i = 1; i < array.length; i++){
  if( array[i] !== re[re.length-1])
  {
   re.push(array[i]);
  }
 }
 return re;
}
Copy after login

5. Optimize array traversal method

From a foreign blog post, the implementation code of this method is quite cool;

Implementation idea: Get the rightmost value without duplication and put it into a new array. (When duplicate values ​​are detected, the current loop is terminated and the next round of judgment of the top-level loop is entered)

// 思路:获取没重复的最右一值放入新数组
function unique5(array){
 var r = [];
 for(var i = 0, l = array.length; i < l; i++) {
  for(var j = i + 1; j < l; j++)
   if (array[i] === array[j]) j = ++i;
  r.push(array[i]);
 }
 return r;
}
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

Using laravel5.3 vue to make favorites function

Data transfer and vue.js Detailed explanation of data distribution steps

The above is the detailed content of What are the ways to delete duplicate elements from an array in JS. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!