Javascript array unique value

Removing duplicate elements from arrays such that each element only appears once is a typical operation. The Array.prototype.filter() method, along with a few additional strategies, can be used to do this.

Javascript array unique value

Using the Array.prototype.filter() method is the first step in eliminating duplicates from an array. The specified function’s test-passing items are all included in a new array that is created using this method. In this situation, the function will determine whether an element is already present in the new array and, if not, add it.

Here is an example of how to use the filter method to remove duplicates from an array:

Copy codelet numbers = [1, 2, 3, 4, 5, 1, 2, 3];
let uniqueNumbers = numbers.filter(function (item, index, array) {
    return array.indexOf(item) === index;
});
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]

Using the Set object is another method of getting the same outcome. A set is a grouping of distinctive values. Any duplicates will be automatically removed by the Set constructor when the array is passed to it. The spread operator can then be used to transform it back into an array.

let numbers = [1, 2, 3, 4, 5, 1, 2, 3];
let uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]

Another way to remove duplicates from an array is by using the for loop and if condition to check if an element is already in the new array, if it’s not then push it to the new array.

let numbers = [1, 2, 3, 4, 5, 1, 2, 3];
let uniqueNumbers = [];
for (let i = 0; i < numbers.length; i++) {
    if (uniqueNumbers.indexOf(numbers[i]) === -1) {
        uniqueNumbers.push(numbers[i]);
    }
}
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]

Finally, there are various JavaScript methods for eliminating duplicates from an array. The most popular techniques for doing this task include the Array.prototype.filter() method, Set object, and for loop with if condition.

About Tech Flow Zone

Leave a Reply

Your email address will not be published. Required fields are marked *