javascript获取最后一个重复值索引javascript

时间:2016-02-02 19:07:04

标签: javascript arrays

我有一个像这样的阵列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]

所以它包含重复的值。在这里的最后一个索引值为 ' 0'是' 3',
' 1'是' 4',
' 2'是' 5',
' 3'是' 13',等等。
我计算了总重复值

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


但我想知道最后一个重复值索引。请帮帮我 提前谢谢

4 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:1)

简单循环并检查下一个索引是否不同

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

答案 2 :(得分:0)

那么,你可以做的是检查一个值是否重复(count > 1),然后使用forEach的第二个参数来记住它。类似的东西:

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}

如果您想要所有值的最后一个索引,而不仅仅是重复,则可以省略count > 1检查:

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}

答案 3 :(得分:0)

Array.prototype.lastIndexOf()在这里派上用场了:

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}

这也适用于未排序的输入数组。