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

js remove duplicate values ​​from array

王林
Release: 2020-05-31 16:57:05
forward
3026 people have browsed it

js remove duplicate values ​​from array

We can use the indexOf() method to remove duplicate values ​​in the array.

Idea: First create a new array, then loop through the array to be duplicated, then use the new array to find the value of the array to be duplicated, if not found, use .push to add it to the new array, and finally Just return the new array.

Specific code:

function fun(arr){
    let newsArr = [];
    for (let i = 0; i < arr.length; i++) {
        if(newsArr.indexOf(arr[i]) === -1){
            newsArr.push(arr[i]);
        }
    }
    return newsArr;
}
Copy after login

You can also use the splice method to remove duplicate values.

Idea: This method is a bit imitating bubbling. Two layers of loops. The outer loop traverses the array, and the inner loop compares the values. If there are similarities, use splice to remove them and return the processed array.

Specific code:

function fun(arr){
    for (let i = 0; i < arr.length; i++) {
        for(let j = i+1; j < arr.length; j++){
            if(arr[i]==arr[j]){
                arr.splice(j,1);          j--;
            }
        }
    }
    return arr;
}
Copy after login

Recommended tutorial: js entry tutorial

The above is the detailed content of js remove duplicate values ​​from array. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
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