Suppose you have a list like this:
[1, 1, 2, 2, 1, 2, 2, 2]
What's the most efficient way to remove repeated data (not duplicates) so no element appears after itself? For this example, the result should be:
[1, 2, 1, 2]
For example, this could be solved with filter or a for loop remembering the last element. But is there something more elegant? Or which option is most efficient?
for loop:
const arr = [1, 1, 2, 2, 1, 2, 2, 2];
const result = [arr[0]];
let lastElement = arr[0];
for (let i = 1, n = arr.length; i < n; ++i) {
if (arr[i] !== lastElement) {
lastElement = arr[i];
result.push(lastElement);
}
}
filter:
const result = [1, 1, 2, 2, 1, 2, 2, 2].filter((element, index, arr) => element !== arr[index - 1]);

