仅返回不匹配的ID-javascript

hec6srdp  于 2021-09-23  发布在  Java
关注(0)|答案(5)|浏览(297)

我有两个对象,arr1和arr2。arr1来自数据库,而arr2将被导入。导入arr2时,显示与arr1不匹配的ID。

var arr1 = [
  {
    "department": "acdc",
    "employeeId": "10100999"
  },
  {
    "department": "asds",
    "employeeId": "10103227"
  },
  {
    "department": "dsds",
    "employeeId": "10103509"
  },
  ...... 1000 entries.
]
var arr2 = 
[
  {
    "department": "acdc",
    "employeeId": "101"
  },
  {
    "department": "asds",
    "employeeId": "1010"
  },
  {
    "department": "dsds",
    "employeeId": "10103509"
  }
]

迪帕利
“找不到ID 101、1010的记录”。
我试过的。

var array1 = app.arr2.filter(function (entry1) {
            return arr1.some(function (entry2) {
                return entry1.employeeId != entry2.employeeId;
            });
        });
       console.log("no records found for Ids =", array1);
m4pnthwp

m4pnthwp1#

你离它很近了。把丢失的东西存起来 employeeId 将其复制到数组,然后打印它。

var arr1=[{department:"acdc",employeeId:"10100999"},{department:"asds",employeeId:"10103227"},{department:"dsds",employeeId:"10103509"}];
var arr2=[{department:"acdc",employeeId:"101"},{department:"asds",employeeId:"1010"},{department:"dsds",employeeId:"10103509"}];

const missing = [];
arr2.forEach(item => {
  const exists = arr1.find(x => x.employeeId === item.employeeId);

  if (!exists) missing.push(item.employeeId);
});

console.log("no records found for Ids = " + missing.join(', '));
zzlelutf

zzlelutf2#

你到底想达到什么目的?从中返回所有元素 arr2 其中没有匹配的id arr1 ?

const arr1 = [1,2,3]
const arr2 = [2,3,4]

function matches(x, y) {
  return x === y; // add your matching function here
}

const arr = arr2.filter(x => !arr1.find(y => matches(x,y)));

console.log(arr);

这将从中返回所有元素 arr2 在中找不到 arr1 根据定义的匹配函数

kxxlusnw

kxxlusnw3#

const items = arr2.filter((item) => {
 const record = arr1.find((temp) => temp.employeeId === item.employeeId);
 if(!record){
   return item;
 }
});

console.log(items);
efzxgjgh

efzxgjgh4#

我还需要做同样的事情,以下代码对我有效:

let arrayWithDistinctIds= arr1.filter(
  o1 =>
    !arr2.find(
      o2=> +o1.employeeId=== +o2.employeeId,
    ),
);
console.log('Array of objects whose ids are not equal',
arrayWithDistinctIds)
z9gpfhce

z9gpfhce5#

let notFound = [];
app.arr2.forEach(entry1 => {
    let missing = arr1.filter(entry2 => {
        return entry2.employeeId != entry1.employeeId;
    })
    if(missing.length == 0){
        notFound.push(entry1.employeeId)
    }
})
console.log(`no records found for Ids = ${notFound.join(', ')}`)

相关问题