比较两个数组并添加新标志

时间:2019-10-04 16:55:44

标签: javascript arrays compare

我有两个结构相同的数组。

我必须对它们进行比较,如果在第一个数组(按ID)中找到第二个数组中的项,则应将标志 isNew 设置为 true -否则设置为 false

const arr1 = [
    {
        id: 1,
        text: 'Text 1'
    },
    {
        id: 2,
        text: 'Text 2'
    },
    {
        id: 3,
        text: 'Text 3'
    }
];

const arr2 = [
    {
        id: 2,
        text: 'Text 2'
    }
];

const result = [
    {
        id: 1,
        text: 'Text 1',
        isNew: false
    },
    {
        id: 2,
        text: 'Text 2',
        isNew: true
    },
    {
        id: 3,
        text: 'Text 3',
        isNew: false
    }
];

2 个答案:

答案 0 :(得分:3)

您可以通过组合module = tf.keras.layers.TimeDistributed(hub.KerasLayer(hub.Module(use_url)))(seq) map轻松地做到这一点:

find

答案 1 :(得分:1)

这是一种方法:

const arr1Ids = [];

arr1.forEach((obj)=>{
  arr1Ids.push(obj.id);
});

arr2.forEach((obj)=>{
  if ( arr1IdArr.includes(obj.id) ) {
    result.forEach((rObj)=>{
      if ( rObj.id === obj.id ) {
        rObj.isNew = true;
      }
    })
  }
})

尽管我赞成GeorgeMA的回答,因为它更简洁