比较项目并将其添加到对象数组 [英] comparing and adding items to array of objects

查看:111
本文介绍了比较项目并将其添加到对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码应该:

1)遍历两个数组,

2)如果两个数组中都存在一项,则将其值添加到第一个数组中类似项的值,

2) if an item exist in both arrays, add its value to the value of the similar item in the first array,

3)如果在arr2中找到了该项目,但在arr1中找不到,则将该项目添加到arr1中.当两个数组的大小相同时,我的代码可以正常工作,但这是我使用不同大小的数组得到的.

3) if the item is found in arr2 but not arr1, add the item to arr1. My code works as desired when both arrays have the same size, but this is what I get with arrays of different size.

结果:

[[42,保龄球"],[4,脏袜子"],[2,猫"],[6,杯子"],[2, 脏袜子"],[3,破布"]]

[[42, "Bowling Ball"], [4, "Dirty Sock"], [2, "cat"], [6, "mugs"], [2, "Dirty Sock"], [3, "rags"]]

应为:

[[42,保龄球"],[4,脏袜子"],[2,猫"],[3,抹布"],[3, 杯子"]]

[[42, "Bowling Ball"], [4, "Dirty Sock"], [2, "cat"], [3, "rags"], [3, "mugs"]]

这是我的代码:

function updateInventory(arr1, arr2) {
  for (var i = 0; i < arr1.length; i++) {
    for (var j = i; j < arr2.length; j++) {
      if (arr1[i][1] === arr2[j][1]) {
        arr1[i][0] += arr2[j][0];
      }
      if (arr1[i].indexOf(arr2[j][1]) === -1) {
        arr1.push(arr2[j]);
      }
      if (arr2.length > arr1.length) {
        arr1.push(arr2[arr2.length -1]);
      }
      else
        break;
    }
  }
  return arr1;
}

var curInv = [
    [21, "Bowling Ball"],
    [2, "Dirty Sock"],
    [2, "cat"],
];

var newInv = [
    [21, "Bowling Ball"],
    [2, "Dirty Sock"],
    [3, "rags"],
    [3, "mugs"]
];

updateInventory(curInv, newInv);

这是什么问题?

推荐答案

您可以使用哈希表作为清单,并检查并更新currInv.

You could use a hash table for the inventory and check against and update currInv.

var curInv = [[21, "Bowling Ball"], [2, "Dirty Sock"], [2, "cat"], ],
    newInv = [[21, "Bowling Ball"], [2, "Dirty Sock"], [3, "rags"], [3, "mugs"]],
    inventory = Object.create(null);

curInv.forEach(function (a) {
    this[a[1]] = a;
}, inventory);

newInv.forEach(function (a) {
    if (!this[a[1]]) {
        this[a[1]] = [0, a[1]];
        curInv.push(this[a[1]]);
    }
    this[a[1]][0] += a[0];
}, inventory);

console.log(curInv);

.as-console-wrapper { max-height: 100% !important; top: 0; }

这篇关于比较项目并将其添加到对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆