FCC高级编程之Inventory Update

Inventory Update

Compare and update the inventory stored in a 2D array against a second 2D array of a fresh delivery. Update the current existing inventory item quantities (in arr1). If an item cannot be found, add the new item and quantity into the inventory array. The returned inventory array should be in alphabetical order by item.

这次是对2维数组的操作。更新第一个数组,如果值不存在则添加,最后按照字母表顺序排列。

下面是给出的两个数组,curInv是第一个参数数组,newInv是第二个。

let curInv = [
    [21, "Bowling Ball"],
    [2, "Dirty Sock"],
    [1, "Hair Pin"],
    [5, "Microphone"]
];

let newInv = [
    [2, "Hair Pin"],
    [3, "Half-Eaten Apple"],
    [67, "Bowling Ball"],
    [7, "Toothpaste"]
];

可以看出,数组每一项元素都有两个子元素,一个是数字子元素,另一个是字符串子元素。当字符串子元素存在时,更新数字子元素,其值为原先两个数字子元素的和。

数组中既有数字,又有字符串,而且两个数组的字符串子元素顺序并不一致,直接采用数组遍历会很麻烦,因而这里采用将数组转换成对象来进行遍历操作。

function updateInventory(arr1, arr2) {
  let obj = {};

  for (let i in arr1) {
    obj[arr1[i][1]] = arr1[i][0];
  }

  for (let i in arr2) {
    obj.hasOwnProperty(arr2[i][1]) ? obj[arr2[i][1]] += arr2[i][0] : obj[arr2[i][1]] = arr2[i][0];
  }
}

上述操作后,得到的对象已经基本更新完了,但输出要求是数组,且要按照字母表顺序排列。那么采用push()方法将对象变为数组,采用sort()方法排序。

function updateInventory(arr1, arr2) {
  let obj = {};
  let arr = [];

  for (let i in arr1) {
    obj[arr1[i][1]] = arr1[i][0];
  }
  for (let i in arr2) {
    obj.hasOwnProperty(arr2[i][1]) ? obj[arr2[i][1]] += arr2[i][0] : obj[arr2[i][1]] = arr2[i][0];
  }

  for (let i in obj) {
    arr.push([obj[i], i]);
  }

  return arr.sort((val1, val2) => {
    return val1[1].charCodeAt(0) - val2[1].charCodeAt(0);
  });
}

运行一下,得到的结果如下图所示。

Inventory Update测试结果图

转载于:https://www.cnblogs.com/laoho/p/7801958.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值