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 [email protected]
What is arrow function in Javascript
An arrow function is short function expr...Create Function in Python with Example
Python Functions In this tutori...Remove a Package from Laravel using Composer
Composer is dependency manager for PHP p...How to disable or enable a form element using jQuery
Use the jQuery prop() method...JavaScript vs jQuery Differences
When new developer starts learning in We...