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
How to get all the keys of an associative array in PHP
Use the PHP array_keys() funct...How to Create Component in Angular 9?
What makes Angular 9 component so signif...How to Detect Change in a Text Input Box in jQuery
Use the input Event You can bind the&...How to integrate paypal payment gateway in laravel 5.4
Hello, today laravelcode share with you...How to get substring from a string using jQuery
Use the JavaScript substring() ...