0

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?

1
  • 3
    with lastIndex ...? Commented Dec 23, 2019 at 17:01

1 Answer 1

2

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.