Home  >  Article  >  Web Front-end  >  js remove duplicate values ​​from array

js remove duplicate values ​​from array

王林
王林forward
2020-05-31 16:57:053028browse

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;
}

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;
}

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!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete