freecodecamp//Algorithm-2 update inventory


1. For the specific requirements of the project, see:

https://learn.freecodecamp.one/coding-interview-prep/algorithms/inventory-update/

2. Code details

JS

function updateInventory(arr1, arr2) {
    arr2.forEach((newItem,newIndex) => {
        arr1.forEach((curItem,curIndex) => {
            if (newItem[1] === curItem[1]) {
                curItem[0] += newItem[0]
                arr2.splice(newIndex, 1)
            }
        })
    })

    return arr1.concat(arr2).sort(function(a,b) {
        if (a[1] > b[1]) {
            return 1;
        } else if (a[1] < b[1]) {
            return -1;
        } else {
            return 0
        }
    })
}

// 两个货物列表示例
var curInv = [
    [21, "Bowling Ball"],
    [2, "Dirty Sock"],
    [1, "Hair Pin"],
    [5, "Microphone"]
];

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

updateInventory(curInv, newInv);
//[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]

Three, harvest

  1. The use of array.forEach() function can condense a lot of code. The difference with the array.map() function is that the map function will not change the original array, while the forEach function will replace the original array; https://www.w3school.com.cn/jsref/jsref_sort.asp
  2. The array.prototype.sort() function, the string is sorted by the first letter of complexity, and the numbers can be concise; among them, if the sort function returns a-b, it means sorting from small to large, that is, a-b returns -1, which is the default Sorting method; vice versa, sorting from largest to smallest. https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Four, impressions

It’s been a long time to do this question, and sometimes it’s easy to get caught up in the horns, but I can’t do it all the time, and I can’t find the problem, so it’s easy to waste a long time. In the future, you have to give yourself a time limit to do the questions. When you really can't do it, you should go to see how others solve it with questions, refer to and learn from others' ideas, and continue to improve.


*There are still many shortcomings in the code. We hope to put forward different opinions and communicate with each other. *

Guess you like

Origin blog.csdn.net/weixin_37877794/article/details/108493691