comparing and adding items to array of objects

前端 未结 4 2002
闹比i
闹比i 2021-01-25 04:13

The below code is supposed to:

1) go through the two arrays,

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

4条回答
  •  孤街浪徒
    2021-01-25 04:42

    You are over-complicating things I think. Here's a working snippet.

    function updateInventory(arr1, arr2) {
      for (var i = 0; i < arr2.length; i++) {
        var matchFound = false;
        for (var j = 0; j < arr1.length; j++) {
          if (arr1[j][1] === arr2[i][1]) {
            arr1[j][0] += arr2[i][0];
            matchFound = true;
          }
        }
    
        if (!matchFound) {
          arr1.push(arr2[i]);
        }
      }
      return arr1;
    }
    
    
    var curInv = [
      [21, "Bowling Ball"],
      [2, "Dirty Sock"],
      [2, "cat"],
    ];
    
    var newInv = [
      [21, "Bowling Ball"],
      [2, "Dirty Sock"],
      [3, "rags"],
      [3, "mugs"]
    ];
    
    console.log(updateInventory(curInv, newInv));

    What it does

    1. Loop through all of the elements in arr2.
    2. Loop through all of the elements in arr1.
    3. If a match is found, add the number of items in arr2 to the corresponding value in arr1.
    4. If no match is found, add that element in arr2 to arr1.

提交回复
热议问题