【问题标题】:compare two array of objects with keys and if not found add it to the array将两个对象数组与键进行比较,如果找不到,则将其添加到数组中
【发布时间】:2019-01-19 19:11:09
【问题描述】:
array1 =  [
    {id: 1, height: 178}, {id: 1, height: 176},
    {id: 2, height: 168},{id: 2, height: 164}
]

array2 =  [
    {id: 1, height: ''},{id: 1, height: ''},
    {id: 2, height: ''},{id: 2, height: ''}, 
    {id: 3, height: ''}, {id: 3, height: ''}, 
    {id: 4, height: ''}, {id: 4, height: ''}
]

resultArray  = [
    {id: 1, height: 178},{id: 1, height: 176},
    {id: 2, height: 168},{id: 2, height: 164}, 
    {id: 3, height:''}, {id: 3, height: ''}, 
    {id: 4, height: ''}, {id: 4, height: ''}
]

我希望将 array1 的 id 与 array2 的 id 进行比较,如果 array1 中缺少任何对象,那么我们将其添加到该数组中。你能建议我怎么做吗?

谢谢

【问题讨论】:

标签: javascript ecmascript-6


【解决方案1】:

1-保存第一个数组的长度

2-遍历第二个数组项

3-如果id不存在或其索引大于数组长度,则将item推送到第一个数组。

let array1 = [{ id: 1, height: 178 }, { id: 1, height: 176 }, { id: 2, height: 168 }, { id: 2, height: 164 }], array2 = [{ id: 1, height: '' }, { id: 1, height: '' }, { id: 2, height: '' }, { id: 2, height: '' }, { id: 3, height: '' }, { id: 3, height: '' }, { id: 4, height: '' }, { id: 4, height: '' }],
  arr1Length = array1.length;

array2.forEach(function(itm) {
  let index = array1.findIndex(function(it) {
    return it.id == itm.id;
  });
  if (-1 == index || arr1Length <= index) {
    array1.push(itm)
  }
});

console.log(array1)

【讨论】:

    【解决方案2】:
    1. 使用Array.prototype.reduce()Array.prototype.map() 之类的方法从array1 创建id 属性中的Set
    2. array2 中过滤掉不在Set 中的条目
    3. array1 与过滤结果连接

    const array1 =  [{id: 1, height: 178},{id: 1, height: 176},{id: 2, height: 168},{id: 2, height: 164}]
    const array2 =  [{id: 1, height: ''},{id: 1, height: ''},{id: 2, height: ''},{id: 2, height: ''}, {id: 3, height: ''}, {id: 3, height: ''}, {id: 4, height: ''}, {id: 4, height: ''}]
    
    // Step #1
    const knownIds = array1.reduce((set, {id}) => set.add(id), new Set())
    
    // Steps 2 and 3
    const resultArray = array1.concat(array2.filter(({id}) => !knownIds.has(id)))
    
    console.info(resultArray)

    【讨论】:

      【解决方案3】:

      我建议使用一组array1 的键来快速查找。请注意,这会改变 array1:

      const array1 = [{id: 1, height: 178},{id: 1, height: 176},{id: 2, height: 168},{id: 2, height: 164}]
      const array2 = [{id: 1, height: ''},{id: 1, height: ''},{id: 2, height: ''},{id: 2, height: ''}, {id: 3, height: ''}, {id: 3, height: ''}, {id: 4, height: ''}, {id: 4, height: ''}]
      
      const ids = new Set(array1.map(e => e.id));
      
      array2.forEach(e => {
        if (!ids.has(e.id)) {
          array1.push(e);
        }
      });
      
      console.log(array1);

      【讨论】:

      • 不错!我感觉有一种比使用reduce() 更好的方法来构建Set
      • 太棒了!!这就是我要找的。非常适合我。非常感谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-15
      • 1970-01-01
      • 2018-02-06
      • 2020-07-31
      • 1970-01-01
      • 1970-01-01
      • 2017-03-04
      相关资源
      最近更新 更多