htoniv
htoniv

Reputation: 1668

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

Upvotes: 4

Views: 3798

Answers (4)

nem035
nem035

Reputation: 35491

Well, what you can do is check if a value is a duplicate (count > 1) and then use the second parameter of forEach which is the index to remember it. Something like:

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 counts = {};
var indexes = {};
arr.forEach(function(x, idx) {
  counts[x] = (counts[x] || 0) + 1;
  if(counts[x] > 1) { indexes[x] = idx; } // check if a value is a duplicate and update its index
});

// logs the last index of all duplicate values
console.log(indexes); // {0: 3, 3: 13, 4: 15, 5: 22}

If you want the last index of all values, not just duplicates, you can omit the count > 1 check:

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 counts = {};
var indexes = {};
arr.forEach(function(x, idx) {
  counts[x] = (counts[x] || 0) + 1;
  indexes[x] = idx; // update value index
});

// logs the last index of all values
console.log(indexes); // {0: 3, 1: 4, 2: 5, 3: 13, 4: 15, 5: 22}

Upvotes: 0

TimoStaudinger
TimoStaudinger

Reputation: 42460

Array.prototype.lastIndexOf() comes in handy here:

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 out = {};

arr.forEach(function(item) {
  if(!out.hasOwnProperty(item)) {
    out[item] = arr.lastIndexOf(item);
  }
});

console.log(out); // Object {0: 3, 1: 4, 2: 5, 3: 13, 4: 15, 5: 22}

This will also work for unsorted input arrays.

Upvotes: 0

Shaun
Shaun

Reputation: 2052

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

Upvotes: 7

epascarello
epascarello

Reputation: 207511

Simple loop and check to see if next index is different

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 indexes = arr.reduce(function(result, cur, ind, arr){
   if (ind+1===arr.length || cur != arr[ind+1]) {  //check to see if last or different
       result.push(ind);  //if different, store the index
   }
   return result;
},[]);
console.log(indexes);

Upvotes: 1

Related Questions