Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript get the last duplicate value index javascript

I have an array to be like this
var arr = [0, 0, 0, 0, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 5, 5, 5, 5, 5, 5, 5].

so it contains duplicate values. In here last index value of
'0' is '3',
'1' is '4',
'2' is '5',
'3' is '13',
and so on.
And i counted total duplicate values

var counts = {};
arr.forEach(function(x) { counts[x] = (counts[x] || 0)+1; })


but i want to know last duplicate value index only. please help me.
thanks in advance

like image 568
htoniv Avatar asked Feb 07 '23 20:02

htoniv


1 Answers

var arr = [0, 0, 0, 0, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 5, 5, 5, 5, 5, 5, 5];
var existingItems = {};

arr.forEach(function(value, index) {
    existingItems[value] = index;
});

console.log(existingItems);
like image 70
Shaun Avatar answered Feb 10 '23 23:02

Shaun