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
Man thanks for this, still hard to understand but i'm gonna keep pushing
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
I tried here and the result shows "the function updateInventory should return an array", and the test is not ok...
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;
}
thank you very much
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;
}