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]);
3
Answers
Just filter with comparing with the previous item:
Reduce and filter are normally slower for large arrays than for loops
JSPerf on mine, Alexander’s and your code: https://jsperf.app/popose/2
Your for loop is faster than this (but not by much)
Your code seems quite optimal. Just one remark: it will fail for an empty array as input, so I would suggest adding a guard for that.
If it is acceptable to perform the action inplace, mutating the input array instead of creating a new one, you can still get some time gain:
See performance tests at https://jsperf.app/popose/3 (added test case to mplungjan’s)