-1

I want to iterate an array and keep only one value if there are more found with the same value.

Example:

const arrayElement = ['red', 'white', 'blue', 'blue'];

To

const arrayElement = ['red', 'white', 'blue'];

How can I do that with vanilla javascript?

Always Helping
  • 13,956
  • 4
  • 11
  • 27
Andrei
  • 11
  • 2

2 Answers2

1

You can remove duplicate from your array via multiple ways

Using Set

Simple and easy way use new Set to remove duplicates from your arrays

Run snippet below.

const arrayElement = ['red', 'white', 'blue', 'blue']; 

const unique = [...new Set(arrayElement)];

console.log(unique)

Using .filter

const arrayElement = ['red', 'white', 'blue', 'blue']; 

const removeDup = arrayElement.filter(function(i, x) {
    return arrayElement.indexOf(i) == x;
})

console.log(removeDup)
Always Helping
  • 13,956
  • 4
  • 11
  • 27
0

Try with Set to remove duplicates from your existing array and keeping only one,

const arrayElement = ['red', 'white', 'blue', 'blue'];
console.log([...new Set(arrayElement)]);
Always Sunny
  • 32,751
  • 7
  • 52
  • 86