Skip to content

Instantly share code, notes, and snippets.

@angle943
Created February 3, 2020 06:09
Show Gist options
  • Save angle943/4d3e6e848ca11299e1ae493cff176528 to your computer and use it in GitHub Desktop.
Save angle943/4d3e6e848ca11299e1ae493cff176528 to your computer and use it in GitHub Desktop.
Javascript Freecodecamp Algorithm #28: Inventory Update
function updateInventory(arr1, arr2) {
const obj1 = arr1.reduce((acc, [amt, name])=>({
...acc,
[name]: amt
}), {});
const obj2 = arr2.reduce((acc, [amt, name])=>({
...acc,
[name]: amt
}), {});
for (const name in obj2) {
if (name in obj1) {
obj1[name] += obj2[name];
} else {
obj1[name] = obj2[name];
}
}
const output = [];
for (const name in obj1) {
output.push([obj1[name], name]);
}
return output.sort((arr1, arr2) => arr1[1].localeCompare(arr2[1]));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment