


5 algorithm implementations for js array deduplication_javascript skills
1. Array traversal method
The simplest method of deduplication, implementation idea: Create a new array, traverse the incoming array, and add the value if it is not in the new array; Note: Determine whether the value is in The array method "indexOf" is an ECMAScript5 method, which is not supported by IE8 and below. You need to write more code to be 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; }
2. Object key-value pair 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, and when traversing the incoming array, judge the value Is it 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; }
3. Array subscript judgment method
You still have to call "indexOf" and the performance is similar to method 1. Implementation idea: If the i-th item of the current array first appears at a position other than i in the current array, then it means that the i-th item Item i 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; }
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; }
5. Optimize array traversal method
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) Recommended
// 思路:获取没重复的最右一值放入新数组 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; }
Determine whether the browser supports indexOf. indexOf is a new method of ecmaScript5. It is not supported by IE8 and below (including IE8, IE8 only supports part of 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; } }
The above are 5 JS array deduplication algorithm implementations provided for you. I hope it will be helpful to your learning.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...
