How to use for loop In Javascript
for loop method checked each value of the original array (listArray) with each value of the output array (outputArray) where the duplicate values are removed. If the current value does not exist in the output array with unique values, then add the element to the output array.
Example: This example generates a unique array of string values.
// Creating a 3x4 two-dimensional array
let Arr = [
"Manish", "Chandan", "Piyush",
"Sunil", "Pankaj", "Piyush",
"Pankaj", "Tiny", "Chandan",
"Manish"];
let outputArray = [];
// Count variable is used to add the
// new unique value only once in the
// outputArray.
let count = 0;
// Start variable is used to set true
// if a repeated duplicate value is
// encontered in the output array.
let start = false;
for (let j = 0; j < Arr.length; j++) {
for (let k = 0; k < outputArray.length; k++) {
if (Arr[j] == outputArray[k]) {
start = true;
}
}
count++;
if (count == 1 && start == false) {
outputArray.push(Arr[j]);
}
start = false;
count = 0;
}
console.log(outputArray);
Output
[ 'Manish', 'Chandan', 'Piyush', 'Sunil', 'Pankaj', 'Tiny' ]
How to get all unique values (remove duplicates) in a JavaScript array?
We are going to learn How to get all unique values (remove duplicates) in a JavaScript array. Given an array with various values, our objective is to filter out any duplicates and display the resulting array in the console.
We can get all unique values in a JavaScript array in the following ways:
Table of Content
- Method 1: Using for loop
- Method 2: Using the Array filter() method:
- Method 3: Using set() Method
- Method 4: Using reduce() Method
- Method 5: Using forEach() Method
- Method 6: Using indexOf() Method
- Method 7: Using Underscore.js _.uniq() Function