How to use for loop In Javascript
In the for loop, we only push our unique elements into the array, if it satisfies the condition that the first occurrence index and last occurrence index must be the same. We use the indexOf() method to get the index first occurrence of an element and the lastIndexOf() method to get the last occurrence of an element.
Syntax:
for (let i = start; condition to i;increment or decrement) {
instruction1;
instruction2;
instruction3;
.
.
};
Example: In this example, we will use for loop to filter out the non-unique values in an array using JavaScript.
const array = [1, 2, 2, 3, 4,
5, 6, 6, 7, 8,
8, 8];
console.log(
"Before filtering non unique values: "
+ array);
let unique = [];
for (let i = 0; i < array.length; i++) {
if (array.lastIndexOf(array[i]) === array.indexOf(array[i])) {
unique.push(array[i]);
}
}
console.log(
"After filtering non unique values: "
+ unique);
Output
Before filtering non unique values: 1,2,2,3,4,5,6,6,7,8,8,8 After filtering non unique values: 1,3,4,5,7
How to filter out the non-unique values in an array using JavaScript ?
In JavaScript, arrays are the object using the index as the key of values. In this article, let us see how we can filter out all the non-unique values and in return get all the unique and non-repeating elements.
These are the following ways by which we can filter out the non-unique values in an array:
Table of Content
- Using the filter() method
- Using for loop
- Using Set and filter
- Using the reduce() Method
Contact Us