-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
  • 14,316
  • 4
  • 13
  • 29
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
  • 14,316
  • 4
  • 13
  • 29
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)]);
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103