Find the total sum of numbers associated with strings that are repeated in two separate arrays

Consider the following scenario where I have 2 arrays:

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

The goal is to create an object that will look like this:

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

To achieve this, a function needs to be implemented that iterates over the categories array and populates the result object. The keys of the object should be unique elements from the categories array, while the values should be the corresponding amounts. If there are repeated elements in the categories array, the function should sum up their amounts.

I have attempted various approaches such as using nested forEach loops and for loops without success. Any help or guidance would be greatly appreciated!

Answer №1

If you want to keep both arrays synchronized, you can achieve it using this method:

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 code snippet will give you the desired output:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to automatically interpret and analyze a gruntfile in order to make changes to it and then resave it?

I'm working on a intricate Yeoman Generator and I'm in search of a solution to parse an existing gruntfile. If anyone knows a JavaScript method for parsing a gruntfile, your assistance would be greatly appreciated. ...

Incorporating JavaScript timeout alerts into a dynamic webpage with a running AJAX task

Operating as a single page AJAX application, my system performs a recursive data gathering operation in the background. While the data is being collected, users have the ability to engage with the page even though the database could potentially be quite la ...

What is the best approach to manage dynamic regex values for input types within ngFor loop?

In my project, I have an array of objects containing details for dynamically generating input fields. I have successfully implemented the dynamic input field generation based on the type received from an API. However, I am facing a challenge with matching ...

Display selected divs with dropdown box but show all divs when no option is chosen

I came across a helpful code on this website while working on my own website. After customizing it to my liking, I encountered some issues. My main goal is to have all divs displayed when no value is selected from the dropdown box. Below is the code that I ...

What is the most effective way to obtain the final row of a Google DataTable using JavaScript?

I have data for Temperature, Humidity, and Time that I can retrieve from a database table to use in a DataTable. However, I also want to extract the most recent set of values from the DataTable and display them in console.log. After attempting to output c ...

JavaScript and CSS animations offer dynamic and engaging ways to bring

I'm working on a div section and I want it to come down and rotate when a button is clicked. However, after moving to the bottom, it doesn't rotate as expected but instead returns to its initial position along the Y axis. How can I fix this issue ...

Please ensure that the menu is included within the HTML file

How can I include a menu from menu.html into index.html? The content of menu.html is: <li><a href="home.html">Home</a></li> <li><a href="news.html">News</a></li> In index.html, the code is: <!docty ...

Step-by-step guide on permanently assigning a value in Node.js

I recently started working with node js and I am facing an issue where I need to save an id in a global variable that is required in multiple functions. However, every time the server restarts, the variable gets emptied. Is there a way to persist this va ...

Ways to display an additional field depending on the data in a number input field using jQuery

https://i.sstatic.net/xfNCt.png When working with Woocommerce, I am attempting to dynamically display a certain number of child age fields based on the data entered in the initial child field. By default, these child age boxes are hidden using CSS. How ca ...

Steps for removing an item from an array in MongoDB

Is it possible to remove an object from the mainList array? _id:ObjectId("5fafc5aec2b84c301845c55a"), username:"test", mainList:[ { _id:ObjectId("5fafdf1a5b49510c789af0ae"), n ...

Working with Thymeleaf and DatePicker to establish a minimum date

Looking to establish a minimum selectable date in my datepicker using Thymeleaf. Attempted code: <label th:utext="#{${name}}" th:for="${name}" class="control-label"></label> <div class="input-group input-group-prepend"> <span cla ...

Error: The function 'toEqual' is not recognized by the 'expect' method causing

I've been following along Dan Abramov's Redux tutorial which can be found at () Lesson 9 covers testing and the usage of expect and .toEqual() This is the code I'm working on: var expect = require('chai').expect; var freeze = re ...

Step-by-step guide for building and populating a JavaScript Dictionary

Does anyone know how to create a Dictionary with a key and a list of values pair in Python? I have been able to create dictionaries with a single value for each key, but now I need to store multiple items as values for each key. Here is what I have tried: ...

Having trouble with Angular 2 and localhost/null error while attempting to make an http.get request?

In my Angular 2 webpage, I am using the OnInit function to execute a method that looks like this (with generic names used): getAllObjects(): Promise<object[]>{ return this.http.get(this.getAllObjectsUrl).toPromise().then(response => response. ...

I seem to be facing some difficulty in dynamically calling my buttons in AngularJS

Can you assist me in solving this problem? I am new to Angular and just starting out. Initially, there is only one button on load called "Add list". When the user clicks on this button, they are able to add multiple lists. Each list contains a button labe ...

Tips for determining if a key is present in local storage:

I need to set a key value, but only if it doesn't already exist. In my component1.ts file, I am assigning the key and value in the constructor. However, I want to include a condition that this action should only be taken if the key is not already pre ...

Combining items in Python lists

Suppose we have a string, let's call it s='135', and a list, let's call it A=['1','2','3','4','5','6','7']. How can we extract the values from the list that are also ...

Saving an image source to your local disk: A step-by-step guide

I have included an image code in my HTML file: <span style="display:inline"> <img NAME="anImage" height="250" src="https://chart.googleapis.com/chart?" alt=""> </span> Now, I would like to enhance this by adding a button. ...

The NestJs project fails to display the updates when using the "tsc" command before running either "npm run start" or "npm run start:dev"

As a beginner in nestjs, I decided to start a tutorial to learn more about it. However, whenever I make updates or changes to my code, I don't see any changes reflected in the results. Can someone please assist me with this issue? Below are my tsconfi ...

When using `res.send()`, an error of Type Error may be encountered stating that the callback is not a function. However, despite this error,

I am currently working on a function for my Node.js server, using Express as the framework and MongoDB as the database. This function involves calling two mongoose queries: (1) Retrieving filtered data from one collection (2) Aggregating data from anothe ...