Reputation:
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]
Upvotes: 2
Views: 92
Reputation: 4644
Here it is modifying original array.
const results = [2, 2, 1, 2, 3, 3, 1]
for (let i = 0; i < results.length;)
{
let j = i;
while (j < results.length)
{
if (results[j] === results[i]) j++;
else break;
}
if ((j - 1) > i) results.splice(i, j - i);
else i++;
}
console.log(results);
Upvotes: 1
Reputation: 22703
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]
Upvotes: 0