0

I have an array with the following elements:

A
B
B
C
B

If an item appears more than once, I have to delete all its occurrences. Therefore, it would be like this:

A
C

I have found lots of examples on how to remove the other repeated elements but still leave the "original" one, out of that I couldn't find anything closer to it and I am really lost.

I have thought about saving in a object the following: 1. The item's value; 2. How many times it appears; 3. The position of all the appearances.

If the times appeared was more than 1, I would remove all of the following positions in the array. Is it a good idea? What would be the best way to do it?

Thank you very much!

Diego Fortes
  • 8,830
  • 3
  • 32
  • 42
  • To clarify, you only want to modify the original array, not create a new one with the elements from the original array removed? – Daryl Dec 05 '16 at 18:24
  • One way could be to create a new array and only push original values by check if value already exists in the new array. Maybe not the best solution, but is one way :P – Medda86 Dec 05 '16 at 18:25
  • @Daryl It would be better if it was in a new array :) – Diego Fortes Dec 05 '16 at 18:26

1 Answers1

9

You can do this using filter() and return only unique elements by checking if indexOf is equal to lastIndexOf

var ar = ['A', 'B', 'B', 'C', 'B'];
var result = ar.filter(function(e) {
  return ar.indexOf(e) == ar.lastIndexOf(e);
})

console.log(result)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176