I
I
ignis212021-06-10 22:10:07
JavaScript
ignis21, 2021-06-10 22:10:07

How to remove an element from an array if it repeats the previous one?

There is an array in which different values ​​\u200b\u200bare consecutive, how to remove the next value if it repeats the previous one?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
0
0xD34F, 2021-06-10
@ignis21

Remove from existing array:

for (let i = arr.length; --i > 0; ) {
  if (arr[i] === arr[i - 1]) {
    arr.splice(i, 1);
  }
}

Assemble a new array:
arr.filter((n, i, a) => !i || a[i - 1] !== n)

P
Peter Zenin, 2021-06-10
@Petja

reduce

A
Alexander, 2021-06-10
@Aleksandr-JS-Developer

const arr = [1, 2, 3, 4, 5, 5, 6, 7, 8, 5, 9, 10, 1, 2, 3];

const cleanArr = a =>
  a.reduce( (a, c) => !a.includes( c ) ? (a.push(c), a) : a, []);

console.log( cleanArr( arr ) );
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question