John_ny
John_ny

Reputation: 797

How to find the index of the last duplicated element in the array in Javascript?

I have an array with the items duplicated, say for eg:

var arr = [1,2,3,4,4,4,5,6]
arr.indexOf(4)  => 3 always gives me the first index of the duplicated element in the array.

What is the best approach in finding the index of other duplicated element especially the last one?

Upvotes: 0

Views: 481

Answers (1)

Shiny
Shiny

Reputation: 5055

Use .lastIndexOf()

The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex.

var arr = [1,2,3,4,4,4,5,6];
let index = arr.lastIndexOf(4);

console.log(index)

Alternatively, If you want the lastIndex of every duplicate element, you could do

let arr = [0, 1, 1, 2, 3, 5, 5, 5, 6];

let lastIndexOfDuplicates = arr.reduce((acc, ele, i, o) => {
  if (o.indexOf(ele) !== i) {
    acc[ele] = i;
  }
  return acc;
}, {});

console.log(lastIndexOfDuplicates);

Upvotes: 2

Related Questions