返回比较 Javascript 时存在于两个数组中的对象的索引

Return the index of object that exist in both array when comparing Javascript

本文关键字:对象 索引 数组 于两个 比较 Javascript 存在 返回      更新时间:2023-09-26

------已编辑---------------

我有 2 个对象数组 A、B

var a = [{id:1},{id:2},{id:3},{id:4},{id:5}];
var b = [{id:1},{id:2},{id:3}];

我想删除同时在 A 和 B 中的对象

//after the operation
 a = [{id:1},{id:2},{id:3}];

我想为了做到这一点,我需要在 A 中获取它们的索引以使用 A.splice((,但我就是无法弄清楚我该怎么做。

这是我用来从中获取对象本身的代码JavaScript 中两个对象数组之间的区别

 var onlyInA = A.filter(function(current){
    return res.nodes.filter(function(current_b){
        return current_b._id == current._id
    }).length == 0
过滤器

中的过滤器不是要走的路。你想使用过滤器和一些。

var a = [{id:1},{id:2},{id:3},{id:4},{id:5}];
var b = [{id:1},{id:2},{id:5},{id:6},{id:7}];
var result = a.filter( function(oa) {
  return b.some( function(ob){
    return oa.id===ob.id;
  });
});
a.length = 0;
a.push.apply(a, result);
console.log(JSON.stringify(a));

如果你想使用 splice((,那么向后循环它。

var a = [{id:1},{id:2},{id:3},{id:4},{id:5}];
var b = [{id:1},{id:2},{id:5},{id:6},{id:7}];
for (var i=a.length-1;i>=0;i--) {
    var inB = b.some( function(ob){
      return a[i].id===ob.id;
    });
    if(!inB) {
      a.splice(i,1)
    }
}
console.log(a);

您可以使用哈希表作为对象的 id,并使用它过滤a

var a = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }],
    b = [{ id: 1 }, { id: 2 }, { id: 3 }],
    hash = Object.create(null);
b.forEach(function (item) {
    hash[item.id] = true;
});
a = a.filter(function (item) {
    return hash[item.id];
});
console.log(a);