Created
February 3, 2020 06:09
-
-
Save angle943/4d3e6e848ca11299e1ae493cff176528 to your computer and use it in GitHub Desktop.
Javascript Freecodecamp Algorithm #28: Inventory Update
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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