Skip to content
Advertisement

How can i get the number without repetition?

i want to get the number with only one repitition:

let results = [2, 2, 1, 2, 3, 3, 1]
let pivot = 1
let cont = 0
let unitaries = []
for (var i = 0; i < results.length; i++) {
  if (pivot !== results[i + 1]) {
    pivot = results[i]
    if (cont === 0) {
      unitaries.push(results[i])
      results.splice(i, 1);
    }
    cont++
  }
}
console.log(unitaries)

i want to get [1,2,1], but right now i am getting only [2]

Advertisement

Answer

Just overwrite your original array using Array.prototype.filter:

let results = [2, 2, 1, 2, 3, 3, 1];

results = results.filter(
    (n, i, array) => n !== array[i - 1] && n !== array[i + 1]
);

console.log(results); // [1, 2, 1]
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement