Javascript获取数组中重复元素第一次和最后一次出现的索引

Javascript get the index of the first and last occurrence of a duplicate element in an array

本文关键字:最后一次 索引 第一次 元素 数组 获取 Javascript      更新时间:2023-09-26

我有一个点数组(latlong坐标),其中一些是重复的。对于重复项,重复项将在数组中恰好重复四次。我想知道数组中重复项第一次和最后一次出现的索引。到目前为止,我所做的是:

我正在检查每个元素与旁边的一个(这是一个未排序的数组)

for(var i = 0; i < points.length; i++) {
  for(var j=i+1; j<points.length; j++) {
    if(points[i] == points[j]) {
      var firstOccurrence = points.indexOf(points[i]);
      var lastOccurrence = points.indexOf(points[i], j+1);
      console.log(firstOccurrence);
      console.log(lastOccurrence);
    }
   }
 }

firststoccurrence正确地给出重复的第一个Occurrence的索引,但是打印相同的索引四次(可能通过for循环循环?)lastOccurrence也正确打印,但第一次打印正确的索引,其余三次打印"-1"。我在这里犯了什么错误?我对javascript比较陌生。

编辑:如果我输入

    if(firstOccurrence) {
      console.log(firstOccurrence); //I would do something else here too apart from printing
    }

它留下第一个重复的第一个出现,并打印其余的索引。例如,如果我的数组是:

 points = [4,4,1,8,0,4,4,5,5,2,7,9,5,5,3,3,10,33,21,3,3];

然后输出

   7
   14

省略了第一个出现的重复的索引,该索引为0。是因为内部for循环中的j = i+1吗?

查找重复项的有效方法(不需要遍历数组中的每个元素)是找到对坐标进行散列的方法。然后,您可以使用减速器对每个数组的所有索引进行分组,并轻松找到重复的坐标。

例如,假设您的数据如下:

var data = [
  {lat: 120, lon: 30},
  {lat: 122, lon: 31},
  {lat: 120, lon: 30},
  ...
];
// Create a function which maps each element to a hashable string
function make(d) {
  return d.lat + ':' + d.lon;
}
// Create a reducer which gathers indexes
// here acc is the accumulated object which starts at {}
// d is each item in the array, and i is the index
data.reduce(function(acc, d, i) {
  var key = make(d);
  acc[key] = acc[key].concat(i) || [i] // gather indexes per element
  return acc;
}, {});

现在您有了一个对象,其中包含了键值对中的所有元素及其原始数组中未更改的索引。

编辑:在reduce函数中,我用d代替了acc中的key。

以下是我的两个版本的解决方案:第一个版本很容易理解,但它打印了4次副本。第二个版本使用了像@Jonah Williams提议的map reduce

function printDuplicatesSimple(points) {
    var first, last;
    for (var i = 0; i < points.length; i++) {
        first = points.indexOf(points[i]);
        last = points.lastIndexOf(points[i]);
        print(duplicateToString(first, last));
    }
}
function duplicateToString(first, last) {
    return "(" + first + "," + last + ")";
}
function makeKey(i, arr) {
    var first = points.indexOf(points[i]),
        last = points.lastIndexOf(points[i]);
    return first === last ? -1 : duplicateToString(first, last);
}
function printDuplicatesMapReduce(points) {
    var res = points.reduce(function(dict, currentItem, index, arr) {
        var key = makeKey(index, arr);
        if (key === -1) {
            return dict; //skip
        }
        if (dict.indexOf(key) === -1) {
            dict.push(key);
        }
        return dict;
    }, []);

    print(res);
}
var points = [4, 4, 1, 8, 0, 4, 4, 5, 5, 2, 7, 9, 5, 5, 3, 3, 10, 33, 21, 3, 3];
printDuplicatesSimple(points);

简单版本输出:(0,6)(0, 6)(2, 2)(3)(4, 4)(0, 6)(0, 6)(7, 13)(7, 13)(9, 9)(10,10)(11日11)(7, 13)(7, 13)(20)(20)(16日,16)(17日17)(18岁,18)(20)(20)

Map reduce版本输出:(0, 6),(7、13)、(14日20)