I have an first array:
first_arr = [["кстати", 1], ["скажем", 1], ["блин", 1], ["реально", 1], ["вообще", 1], ["допустим", 1], ["фактически", 1], ["получается", 1]]
And the second:
second_arr = [['кстати', 1], ['скажем', 2], ['реально', 3], ['вообще', 3], ['ладно', 5]]
How can i summarize it to be like:
final_arr = [["кстати", 2], ["скажем", 3], ["блин", 1], ["реально", 4], ["вообще", 4], ["допустим", 1], ["фактически", 1], ["получается", 1], ['ладно', 5]]
CodePudding user response:
You can concatenate the two arrays and reduce
over it, incrementing the count of each key. Then, call Object.entries
on the result:
first_arr = [["кстати", 1], ["скажем", 1], ["блин", 1], ["реально", 1], ["вообще", 1], ["допустим", 1], ["фактически", 1], ["получается", 1]]
second_arr = [['кстати', 1], ['скажем', 2], ['реально', 3], ['вообще', 3], ['ладно', 5]]
const res = Object.entries(first_arr.concat(second_arr).reduce((a, [key, val]) => (a[key] = (a[key] || 0) val, a), {}))
console.log(res)