Home > Web Front-end > JS Tutorial > How to efficiently remove duplicate items from js array

How to efficiently remove duplicate items from js array

PHPz
Release: 2018-09-28 14:27:08
Original
1668 people have browsed it

This chapter will introduce to you how to efficiently remove duplicate items in js arrays. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Method 1: Regular mode

1. Construct a new temporary array to store the results

2. Each time in the for loop, from Take out an element from the original array, use this element to loop and compare it with the temporary array

3. If the element does not exist in the temporary array, store it in the temporary array

How to efficiently remove duplicate items from js array

Method 2: Use the default Js array sort, which is sorted by ASCII;

If you want to arrange it in ascending and descending order:

How to efficiently remove duplicate items from js array

1. Sort the current array first

2. Check whether the i-th element in the current array is the same as the last element in the temporary array. Because it has been sorted, the duplicate elements will be in Adjacent positions

3. If they are not the same, store the element in the result array

How to efficiently remove duplicate items from js array

Method 3:

1. Create a new array to store the results

2. Create an empty object json

3. During the for loop, take out an element each time and compare it with the object. If this If the element is not repeated, it is stored in the result array. At the same time, the content of this element is used as an attribute of the object, assigned a value of 1, and stored in the object created in step 2.

Explanation: As for how to compare, it is to take out one element from the original array each time, and then access the attribute in the object. If the value can be accessed, it means it is repeated.

How to efficiently remove duplicate items from js array

The above is all about how to efficiently remove duplicate items in js arrays. I hope it can give you a reference. For more related tutorials, please visit JavaScript video Tutorial!

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