Skip to content
the poor coder

Remove Duplicates array values in javascript

Poor Man
Published
Reading time
1 min read
On this page

hljs.initHighlightingOnLoad();

Removing Duplicate Array Values in Javascript#

As a web developer, I have often come across situations where I needed to remove duplicate values from an array in Javascript. There are multiple ways to achieve this, and I'll discuss some of them below:

Using Set#

The easiest and most efficient way to remove duplicate values from an array is by using the Set object in Javascript. Here's how you can do it:

Text

let arr = [1, 2, 2, 3, 4, 4, 5];
let uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // Output: [1, 2, 3, 4, 5]
    

Using a For Loop#

You can also remove duplicates from an array by looping through it and checking each value against the rest of the values in the array. Here's an example:

Text

let arr = [1, 2, 2, 3, 4, 4, 5];
let uniqueArr = [];

for (let i = 0; i < arr.length; i++) {
  if (uniqueArr.indexOf(arr[i]) === -1) {
    uniqueArr.push(arr[i]);
  }
}

console.log(uniqueArr); // Output: [1, 2, 3, 4, 5]
    

Using the Filter Method#

You can also use the filter method to remove duplicates from an array. Here's how:

Text

let arr = [1, 2, 2, 3, 4, 4, 5];
let uniqueArr = arr.filter((value, index, self) => {
  return self.indexOf(value) === index;
});

console.log(uniqueArr); // Output: [1, 2, 3, 4, 5]
    

Conclusion#

Removing duplicate values from an array is a common problem in Javascript programming. You can use the Set object, a for loop or the filter method to achieve this. The choice of method depends on your preferences and the specific situation you're dealing with.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC