Oliver
Oliver

Reputation: 3

Compare 2 arrays -one contains strings, the other contains numbers. Sum numbers of repeated strings

I have 2 arrays. Let's say

categories = ["hotels", "transfers","food","transfers"] 
amounts = [1500, 250, 165, 150]

I would like to generate an object that outputs an object...

result = {hotels: 1500, transfers: 400, food: 165}

The function should loop over categories, populate the result object, adding the categories' unique elements as object keys, and the amounts as values. The function should also add the amounts of the repeated keys.

I have tried several things like 2 nested for each on the arrays, for loops, ... but I can't figure out anything that works ...

Upvotes: 0

Views: 38

Answers (1)

Ricardo Gomes
Ricardo Gomes

Reputation: 30

If you have the index of both arrays always in sync, you can do it like:

const categories = ["hotels", "transfers","food","transfers"];
const amounts = [1500, 250, 165, 150];
const result = {};

categories.forEach((category, index) => {
  const doesKeyExist = !!result[category];
  const amount = amounts[index];
  const correctAmount = doesKeyExist ? result[category] + amount : amount;

  result[category] = correctAmount;
}

this will result in what you expect:

result = {hotels: 1500, transfers: 400, food: 165}

Upvotes: 1

Related Questions