Home > Web Front-end > JS Tutorial > Javascript remove duplicate elements from array_javascript tips

Javascript remove duplicate elements from array_javascript tips

WBOY
Release: 2016-05-16 18:28:17
Original
813 people have browsed it

I opened Firebug's console and spent 30 seconds thinking and 30 seconds writing. The results are as follows: (x is the target array, y is the result after removing duplicate elements)

Copy Code The code is as follows:

var x=[1,1,3,4,5,3];
var y=[];
var tArray=function(i,arr){
var yap=false;
for(var j=0;jif(arr[j]==i ){yap=true;break;};
}
if(!yap) arr.push(i);
};
for(var t=0;ttArray(x[t],y);
}
alert(y.length);
alert(y.toString());

The answer is not unique, and there is no standard answer, so the above code is right or wrong. What if the array is an array of complex objects? What if the array contains multiple empty objects {}? You must know that there are many special and even buggy phenomena in js, alert({}=={}) to see what's going on...

Note: If anyone has a standard answer, please post it in the comments for everyone Learn to learn.

The question maker itself will not consider these issues.

Don’t learn to solve problems. The real value is the ability to solve problems efficiently when you encounter problems in actual work.

Additional points that need attention:

There is a problem that should be paid attention to
arr[j]==i You seem to be referring to the equality judgment when the array elements are of type number. ...
But often we may have to make equality judgments on different types... This is an issue that should be considered in practical applications

1!=new Number(1)
null The case of ==undefined

0=="0" and so on

So obviously simple == and === are inappropriate.
One should be implemented independently The equals method does equality judgment... Set the rules according to the requirements

The example I gave is for arrays of type number, and the purpose is to express an attitude towards "what to do in the interview". In practical applications, it should be considered based on actual needs. Unless required by actual work or I am a js academic researcher, I will not implement an equals method independently. Foreign developers often follow a creed: "Do The Simplest Thing That Could Possibly Work", which roughly means "Don't over-design, suitability comes first." My work experience in the past few years often confirms this truth. I don’t know what you think.
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