I need to know if an array in JavaScript has duplicate elements.
Is there any function in the jQuery API that does this? If not, how can I proceed?
I need to know if an array in JavaScript has duplicate elements.
Is there any function in the jQuery API that does this? If not, how can I proceed?
No, there is no function via jQuery that does this. The closest thing to this reality would be .unique () , but only works with elements DOM
.
But you can even develop your own method using .each
and .inArray
.
Take a look:
var times = ["Flamengo","Vasco","Corinthians","Fluminense","Corinthians","Fluminense","Palmeiras","Vasco"];
var timesNaoDuplicados = [];
$.each(times, function(i, elemento){
if($.inArray(elemento, timesNaoDuplicados) === -1) timesNaoDuplicados.push(elemento);
});
//Se "printar" o timesNaoDuplicados: ["Flamengo", "Vasco", "Corinthians", "Fluminense", "Palmeiras"]
If you want to know only if an element is inside an array, use .inArray(elemento, Array)
.
More about .inArray
here .
In short, it returns you the position (index) where the element is inside the array. If it does not find anything, it returns -1.
With the magic of ES6 you can solve your problem with just one line of code. Ex:
var a = ["Ceará","Eusébio","Ceará"];
var b = ["JavaScript",">","All"];
function hasDuplicates(array) {
return (new Set(array)).size !== array.length;
}
hasDuplicates(a);//true
hasDuplicates(b);//false