avatar

Hassan khan

Last updated: March 22,2022

How-to-remove-duplicate-values-from-array-in-javascript?

How to remove duplicate values from array in javascript


There are many ways to remove duplicate values from an array but we will use two easy methods.
1) use of the set method of es6
2) indexOf and filter methods of javascript


1) Set

A set contains unique values, In simple words, a Set is a collection of unique values. When you pass an array of duplicate values it will return a set of unique values. With the help of the spread operator, we will convert it into an array.


The below example demonstrates how to get unique values from the array.

  • First, we have to convert the array into a set.
  • The set will remove the duplicate values.
  • Then, with the spread operator, converted back into an array.

Example

1
2
3
let charsArray = ['A', 'B', 'C', 'A', 'B'];
  let uniqueCharsArray = [...new Set(charsArray)];
  console.log(uniqueCharsArray);

Output

1
[ 'A', 'B', 'C' ]

2) Use of indexOf and filter methods

The indexOf method search value in an array and returns the index of value. If a value is not found in the array then, It will return -1.

Filter method method iterates over the array and returns only those values that pass a specific condition.

In the below example, we have used the indexOf and filter method to remove the duplicated values.

Example

1
2
3
4
let charsArray = ['A', 'B', 'C', 'A', 'B'];
  let uniqueCharsArray = charsArray.filter((value, index) => {
  return charsArray.indexOf(value) === index;
  });

Output

1
[ 'A', 'B', 'C' ]

Share