Home Web Front-end JS Tutorial 5 JavaScript algorithms for removing duplicate elements from an array

5 JavaScript algorithms for removing duplicate elements from an array

Jan 19, 2018 am 09:09 AM
javascript js repeat

This article mainly introduces five commonly used efficient algorithms for deleting duplicate elements of arrays in JavaScript. It summarizes and analyzes several common operating techniques for deleting duplicate elements of arrays in JavaScript in the form of examples. Friends who need it can refer to it. I hope it can help everyone. . Here are 5 methods on how to implement array deduplication in js.

1. Array traversal method

The simplest method to remove duplicates,

Implementation ideas : Create a new array, traverse the incoming array, and add the value 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 supported by IE8 and below. You need to write more for low compatibility Version browser code, 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

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

Implementation idea: Create a new js object and a new array, and when traversing the incoming array, determine whether the value It is the key of the js object. If not, add the key to the object and put it into a new array. Note: 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 the "indexOf" performance and method 1 is almost the same,

Implementation idea: If the i-th item of the current array first appears in a position other than i in the current array, then 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 "sort" method of the native array The sorting results are not very reliable, but this shortcoming has no impact in deduplication that does not pay attention to the 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. Optimizing array traversal method

comes from foreign blog posts, the implementation code of this method 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
Related recommendations:

How about JavaScript Detailed explanation of ideas and code examples for removing duplicate elements in arrays

Recommended summary of several javascript methods to delete duplicate elements

Search in js array Example tutorial of producing repeated elements

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

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to solve the problem of infinite loop of opening web pages in Edge browser How to solve the problem of infinite loop of opening web pages in Edge browser Dec 25, 2023 pm 01:19 PM

Many friends who use the edge browser on win10 have encountered the problem of web pages opening repeatedly, which is a headache. So how to solve it? Let’s take a look at the detailed solutions below. What to do if the edge browser keeps opening web pages repeatedly: 1. Enter the edge browser and click the three dots in the upper right corner. 2. Click "Settings" in the taskbar. 3. Find "Microsoft edge opening method". 4. Click the drop-down menu and select "Start Page". 5. Restart the browser after completion to solve the problem.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

See all articles