Q:

Combine two arrays into key-value pairs and add values if key already exists

I have two arrays (a & b) that I want to combine into one array (obj) with key-value pairs. How can I make it so that if obj does not include key, add that key and corresponding value to obj, but if obj already has that key, add the value of duplicate key to original key value?
var a = ["red", "green", "red", "blue"]
var b = [2, 4, 3, 1]

desired obj = {["red", 5], ["green", 4], ["blue", 1]}

I know keys need to be unique in an array so if I combine the two arrays outright like below, the duplicate keys will disappear, but I'm not sure how to handle the values of duplicate keys and add all values of the same key together.
var obj = {};
for (var i=0; i<a.length; i++) {
    obj[a[i]] = b[i]
}

A:

You need to check if the key already exists in the object so you don't overwrite the previous value

var a = ["red", "green", "red", "blue"]
var b = [2, 4, 3, 1]

var obj = {};
for (var i=0; i<a.length; i++) {
    // if it doesn't exist assign value 0 to it, otherwise use existing value
    obj[a[i]] = obj[a[i]] || 0;
    // then add the new value
    obj[a[i]] += b[i];
}

console.log(obj)

