In-depth study of JavaScript array deduplication problem

In-depth study of JavaScript array deduplication problem

Preface πŸ‘€

Array deduplication should be a very common problem. Since it is common, we should learn about it!

Lest I be embarrassed if I don't know how to do it~ Hehe

Start researching πŸ±β€πŸ

Original 🧢

To deduplicate an array, my initial idea was this: define a new array, complete two layers of for loops, if the data appears for the first time, push it to the new array, if it is repeated, break it, use the value of j to be equal to the length of res to determine that the data is unique, and finally return the new array.

var arr = [1,1,2,3,4,5,6,7,4,3,'1',8,'3','1','3','66']

function unique(arr){
	var res = []
	for(var i = 0; i < arr.length; i++){
		for(var j = 0; j < res.length; j ++){
			if(arr[i] === res[j]){
				break
			}
		}
		// If the data appears for the first time, then after executing the above for statement, the value of j should be equal to the length of res if(j === res.length){
			res.push(arr[i])
		}
	}
	return res;
}

console.log(unique(arr));

Optimizing the original method using indexOf ✍

Let's first take a brief look at indexOf:

The indexOf(item,start) method returns the position of a specified element in an array.

This method will search the array from beginning to end to see if it contains the corresponding element. The search starts at the start of the array or at the beginning of the array (when the start parameter is not specified). If an item is found, the position of the first occurrence of item is returned. The starting position has an index of 0.

If the specified element is not found in the array, -1 is returned.

Seeing this, everyone understands what we are taking advantage of, right? Yes, it is the bold sentence: If the specified element is not found in the array, -1 is returned .

var arr = [1,1,2,3,4,5,6,7,4,3,'1',8,'3','1','3','66']

function unique(arr){
	var res = []
	for(var i = 0; i < arr.length; i++){
		if (res.indexOf(arr[i]) === -1) {
			res.push(arr[i])
		}
	}
	return res;
}

console.log(unique(arr));

Optimize again, filter method πŸŽ‰

As the name implies, filter means filtering. This method creates a new array. The elements in the new array are obtained by checking all elements that meet the conditions in the specified array.

Idea: Use filter instead of a layer of loop in conjunction with indexOf to achieve the filtering effect and directly return the deduplicated array.

var arr = [1,1,2,3,4,5,6,7,4,3,'1',8,'3','1','3','66']

function unique(arr){
	var res = arr.filter(function(item,index,arr){
		return arr.indexOf(item) === index
	})
	return res;
}
console.log(unique(arr));

Change of thinking? Become an ordered array ✨

I wonder if those of you who have been playing Lecture Hall for a few days have had this feeling. When you see an array in a question, your eyes immediately glance forward to see if it is an ordered array or an unordered array.

Back to this question, we make the array to be deduplicated ordered, and the repeated data must be next to each other. Use a variable to store the previous element value, and then loop to determine whether the current value is the same as the previous element value. If not, add it to res.

var arr = [1,1,2,3,4,5,6,7,4,3,'1',8,'3','1','3','66']

function unique(arr){
	var res = []
	var pre
	arr = arr.sort()
	for(var i = 0; i < arr.length; i++){
		if(!i || pre !== arr[i]){
			res.push(arr[i])
		}
		pre = arr[i]
	}
	return res;
}

console.log(unique(arr));

Optimize again, filter🧨

I just realized that filter can also rewrite the sorting here to make it more concise. Let's look at the code directly:

var arr = [1,1,2,3,4,5,6,7,4,3,'1',8,'3','1','3','66']

function unique(arr){
	var res = arr.sort().filter(function(item,index,arr){
		return !index || item !== arr[index - 1]
	})
	return res;
}

console.log(unique(arr));

ES6, Set is coming 🧸

ES6 brings us many benefits, among which map and set are particularly outstanding.

Map objects store key-value pairs. Any value (object or primitive) can be used as a key or a value.

The Set object allows you to store unique values ​​of any type, whether primitive values ​​or object references.

So we can use this feature of Set to perform deduplication processing.

var arr = [1,1,2,3,4,5,6,7,4,3,'1',8,'3','1','3','66']

function unique(arr){
	return Array.from(new Set(arr))
}

console.log(unique(arr));

Note: Set is an object, so it must be converted into an array for return.

If you understand destructuring assignment, you can simplify it a little bit more🧡

var arr = [1,1,2,3,4,5,6,7,4,3,'1',8,'3','1','3','66']

function unique(arr){
	return [...new Set(arr)]
}

console.log(unique(arr));

If you want to know more about destructuring assignment, you can also read this first: Understanding and Application of Destructuring Operators

Previous study, recorded notes 🎨

Keep on being great (arrow functions) πŸ†

var arr = [1,1,2,3,4,5,6,7,4,3,'1',8,'3','1','3','66']
var unique = (arr) => [...new Set(arr)]
console.log(unique(arr));

Finally πŸ“–

From several lines of code at the beginning to one line of code at the end using arrow functions, it is enough to show that only by continuous learning can we write more elegant and concise code.

This is the end of this article about JavaScript array deduplication. For more relevant JavaScript array deduplication content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JS array deduplication details
  • Detailed discussion of several methods for deduplicating JavaScript arrays
  • JavaScript array deduplication solution
  • js implements array flattening
  • JavaScript data flattening detailed explanation
  • JavaScript Interview: How to implement array flattening method
  • 5 JavaScript Ways to Flatten Arrays
  • Introduction to JavaScript array deduplication and flattening functions

<<:  Detailed explanation of MySQL's FreeList mechanism

>>:  Analyze the role of rel="nofollow" in HTML and the use of rel attribute

Recommend

Vue network request scheme native network request and js network request library

1. Native network request 1. XMLHttpRequest (w3c ...

How to make a List in CocosCreator

CocosCreator version: 2.3.4 Cocos does not have a...

Method of realizing automated deployment based on Docker+Jenkins

Use Code Cloud to build a Git code storage wareho...

Pure CSS to achieve automatic rotation effect of carousel banner

Without further ado, let’s get straight to the co...

An article to help you understand jQuery animation

Table of contents 1. Control the display and hidi...

Detailed graphic explanation of sqlmap injection

Table of contents 1. We found that this website m...

Use pure CSS to achieve switch effect

First is the idea We use the <input type="...

How to let https website send referrer https and http jump referrer

This article describes a proposal for a metadata ...

Understanding MySQL Locking Based on Update SQL Statements

Preface MySQL database lock is an important means...

A brief talk about calculated properties and property listening in Vue

Table of contents 1. Computed properties Syntax: ...

How to modify the time zone and time in Ubuntu system

On a Linux computer, there are two times, one is ...

Pure CSS custom multi-line ellipsis problem (from principle to implementation)

How to display text overflow? What are your needs...

Detailed explanation of Vue custom instructions and their use

Table of contents 1. What is a directive? Some co...

Detailed explanation of the basic use of centos7 firewall in linux

1. Basic use of firewalld start up: systemctl sta...