Javascript Freecodecamp Algorithm #28: Inventory Update

Поделиться
HTML-код
  • Опубликовано: 10 сен 2024
  • Learn how to solve freecodecamp javascript algorithms in various ways! This series is up-to-date with all ES6 and beyond javascript notations
    Start from the beginning of this series! - • Javascript Freecodecam...
    Web Developer Roadmap 2020 Edition - • Video
    🗄 Resources:
    Final Code Solution: gist.github.co...
    MDN Sort Method: developer.mozi...
    #javascript #algorithms #freecodecamp

Комментарии • 6

  • @julienaz2274
    @julienaz2274 4 года назад +1

    Man thanks for this, still hard to understand but i'm gonna keep pushing

  • @Lashistoriasdelilith
    @Lashistoriasdelilith 2 года назад

    I can't do all this right now so I'll try with arrays still but you gave me ideas so thank you!! I'll subscribe

  • @Razor046
    @Razor046 Год назад

    I tried here and the result shows "the function updateInventory should return an array", and the test is not ok...

  • @Pedro-dw3if
    @Pedro-dw3if 2 года назад +1

    Here is my solution with commentary:
    function updateInventory(arr1, arr2) {
    const newArr = [...arr1, ...arr2]
    const obj = {}
    // Adding keys and values to the obj
    newArr.forEach((item) => {
    // obj = {newArr[1]: newArr[0]}
    obj[item[1]] = item[0]
    if(obj.hasOwnProperty(item[1])) {
    // if key exists, sum the new value with the current value
    obj[item[1]] += item[0]
    }
    })
    // console.log(obj)
    // Transforming the obj into array and sorting array alphabetically
    const output = Object.entries(obj).sort()
    // console.log(output)
    // Reversing each array
    output.forEach((item) => {
    item.reverse()
    })
    console.log(output)
    return output;
    }

  • @danib5011
    @danib5011 3 года назад

    thank you very much

  • @chitraflorid684
    @chitraflorid684 3 года назад

    I have tried with ES6 Map.
    function updateInventory(currInv, newInv) {
    const invMap = new Map();
    const res = [];
    currInv.forEach(([count, name]) => {
    invMap.set(name, count);
    });
    newInv.forEach(([count, name]) => {
    invMap.set(name, invMap.get(name) + count || count);
    });
    for (const [invName, count] of invMap) {
    res.push([count, invName]);
    }
    res.sort((a, b) => a[1].localeCompare(b[1]));
    return res;
    }