Home > Web Front-end > JS Tutorial > JS code to remove duplicates from two arrays_javascript skills

JS code to remove duplicates from two arrays_javascript skills

WBOY
Release: 2016-05-16 17:10:56
Original
1406 people have browsed it

The first type:

Copy code The code is as follows:

function unique (arr){
var obj = {},newArr = [];
for(var i = 0;i < arr.length;i ){
var value = arr[i];
if(!obj [value]){
obj[value] = 1;
newArr.push(value);
}
}
return newArr;
}

This method stores the value of the array into the object. Therefore, when the array contains object members, the operation fails (the object as the key of the object will be converted into a string).
Second method:
Copy code The code is as follows:

function unique (arr ){
for(var i = 0;i < arr.length;i ){
for(var j = i 1;j < arr.length;j ){
if(arr[ i] === arr[j]){
arr.splice(j,1);
j--}
}
}
return arr;
}

This method is supported even if the incoming array contains objects. Note the '===', but using nested loops, the performance will be worse than the first method.
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