indexOf()
MethodYou can use the indexOf()
method in conjugation with the push()
remove the duplicate values from an array or get all unique values from an array in JavaScript.
Let's take a look at the following example to understand how it basically works:
<script>
// Defining function to get unique values from an array
function getUnique(array){
var uniqueArray = [];
// Loop through array values
for(i=0; i < array.length; i++){
if(uniqueArray.indexOf(array[i]) === -1) {
uniqueArray.push(array[i]);
}
}
return uniqueArray;
}
var names = ["John", "Peter", "Clark", "Harry", "John", "Alice"];
var uniqueNames = getUnique(names);
console.log(uniqueNames); // Prints: ["John", "Peter", "Clark", "Harry", "Alice"]
</script>
Alternatively, you can use the newly introduced ES6 for-of
loop instead of for
loop to perform this filtration very easily, as demonstrated in the following example:
<script>
// Defining function to get unique values from an array
function getUnique(array){
var uniqueArray = [];
// Loop through array values
for(var value of array){
if(uniqueArray.indexOf(value) === -1){
uniqueArray.push(value);
}
}
return uniqueArray;
}
var names = ["John", "Peter", "Clark", "Harry", "John", "Alice"];
var uniqueNames = getUnique(names);
console.log(uniqueNames); // Prints: ["John", "Peter", "Clark", "Harry", "Alice"]
</script>
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on harsukh21@gmail.com
Laravel 7 Guzzle Http Client Request Example
Hello Artisan, in this tutorial i am goi...Make Authentication System with VueJs and Google Firebase
In this tutorial, we will learn how to i...How to Connect MySQL Database in Python?
In this article, I will share with you h...How to play and stop CSS animation using jQuery
Use the jQuery css() method...How to disabled Submit Button after Clicked using jQuery
Often times, users like to press a few t...