Adding elements in an array depending on the values in a separate array

I am currently working on a task that involves summing values in an array of objects based on the Ids present in another array within the same object. Let's assume I have the following queryArray:

const queryArray = [ "1" , "2" ]

and this is the services array from which I would like to sum the fees property values if their Id matches with queryArray:

const services = [
  {
    Id: "1",
    services: "Early Check-In",
    fees: "7500"
  },
  {
    Id: "2",
    services: "Late Checkout",
    fees: "7500"
  },
  {
    Id: "3",
    services: "Airport Chauffeur",
    fees: "25000"
  }
]

So, I want to calculate the total sum of the fees property value in the services array by matching the Ids available in the queryArray. For example, when using the queryArray:

[ "1" , "2" ]

The expected result should be:

15000

If we use:

[ "1" , "3" ]

The expected result would be:

32500

And for:

[ "1", "2" , "3"]

The expected result should be:

40000

As a beginner in javascript, I am struggling to find a solution or even know where to start. Any guidance or suggestion would be greatly appreciated.

Answer №1

Of course, start by using the filter function to sort through the services you require -> Then apply the map function to each service to retrieve its value -> Finally, utilize the reduce function to condense the list into a single number by summing up all elements:

const services = [
  {
    Id: "1",
    services: "Early Check-In",
    fees: "7500"
  },
  {
    Id: "2",
    services: "Late Checkout",
    fees: "7500"
  },
  {
    Id: "3",
    services: "Airport Chauffeur",
    fees: "25000"
  }
]
const ids = ["1" , "2"]

console.log(
  services
    .filter(({Id}) => ids.includes(Id))
    .map(({fees}) => parseFloat(fees))
    .reduce((acc, fees) => acc + fees, 0)
  
)

Answer №2

Verify if the identifier is part of the identification array within the reducer:

const amenities = [
  {
    Id: "1",
    serviceType: "Early Check-In",
    cost: "7500"
  },
  {
    Id: "2",
    serviceType: "Late Checkout",
    cost: "7500"
  },
  {
    Id: "3",
    serviceType: "Airport Chauffeur",
    cost: "25000"
  }
]

const selectionArray = [ "1" , "2" ]

const result = amenities.reduce((totalCost, currentService) => selectionArray.includes(currentService.Id) ? totalCost += +currentService.cost : totalCost, 0)

console.log(result)

Answer №3

Another approach is to utilize the reduce method, where you iterate through each entry and check if the Id matches any value in the queryArray. If there's a match, add the current fees to the running total.

Initialize the starting value as 0.

const services = [{
    Id: "1",
    services: "Early Check-In",
    fees: "7500"
  },
  {
    Id: "2",
    services: "Late Checkout",
    fees: "7500"
  },
  {
    Id: "3",
    services: "Airport Chauffeur",
    fees: "25000"
  }
]

const queryArray = ["1", "2"]

let res = services.reduce(
  (total, curr) => queryArray.includes(curr.Id) ? total + parseInt(curr.fees, 10) : total,
  0
);
console.log(res);

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 it possible to view the code within the .js files located in the api directory of NextJS using web browsers?

Is it possible to view the code of ".js files" in the "api folder" of NextJS using browsers? I came across a post on Stack Overflow where someone asked if Next.js API is back-end, and one of the answers stated: The back-end or server-side of Next.js res ...

List item with React Material UI tooltip

click here for image preview Exploring the idea of incorporating a customized tooltip component using React Material UI. The goal is to leverage the tooltip, list item, and list components provided by React Material UI. I have experimented with utilizing ...

The Socket IO Client is receiving a different object than the one that was sent by the Server

My server side code is sending an object to the client side, but the object received by the client is completely different from what was sent. Let me elaborate: Code Server side code: //Setting up the example var response={}; response.models=[]; respo ...

JavaScript - Merging the two JSON requests into a unified object

Is there a way to merge two different JSON responses into a single object for easy data manipulation? I've explored various solutions, but none seem to align with my current code structure. Given that I'm new to this, it would be incredibly hel ...

React Material UI issue: You cannot render objects as a React child. If you intended to display a group of children, make sure to use an array instead

I am encountering an issue with the code provided below and despite trying various fixes, I am unable to resolve it. componentDidMount() { axios.get('http://localhost:8080/home') .then((response) => { this.setState({ ...

The battle between CSS and jQuery: A guide to creating a dynamic zebra-style table without relying on additional plugins

Is there a better way to create a dynamic zebra styling for table rows while still being able to hide certain elements without losing the styling? In this code snippet, I'm using the CSS :nth-of-type(even) to style even rows but running into issues wh ...

Combining Mongoose OR conditions with ObjectIDs

After querying my Team schema, I am receiving an array of ids which I have confirmed is correct. The issue seems to lie in the fact that both home_team and away_team are ObjectIDs for the Team Schema within my OR statement. Team.find({ 'conferenc ...

Exploring the World of Next.js and Sequelize Model Relationships

Greetings to all the problem-solving enthusiasts out there! I'm currently in the process of revamping a previous project using Next.js, and I've hit a roadblock that has me stumped. My current challenge involves establishing an association betwe ...

After refreshing, the LocalStorage in Angular 2 seems to disappear

Something a little different here :) So, when attempting to log a user in, I am trying to store the access_token and expires in localStorage. It seems to be working "okay". However, if I refresh the page, the tokens disappear. Also, after clicking the log ...

Troubleshooting the issue: AngularJS not functioning properly with radio button selection to show specific div containing input field

Looking for some help with radio buttons: I need the selection of radio buttons to display their respective input boxes. I have included a snippet of my HTML and controller code below. In my controller, I am using ng-change to call a function that uses jQu ...

Clicking on the button will result in the addition of new

Having some trouble with jQuery as I try to dynamically add and remove HTML elements (on click of +) while also making sure each element has a unique name and ID like "name_1", "name_2"... Unfortunately, things aren't quite going as planned. Below i ...

When I click a button in d3 to refresh the data on my bar graph, the text fails to update accordingly

I've successfully created a series of data lists that modify the bargraph. Unfortunately, due to their differing x and y values, they end up printing new values on top of existing ones. Shown below is an image illustrating the issue where x and y val ...

NPM - Include in package.json without installation

Can a command be executed to validate that the package is a legitimate npm package, include it as a dependency in package.json, but refrain from actually installing it? This question arises from the need to utilize a specific package globally and incorpor ...

Have you ever wondered why req.body returns as undefined when using body parser?

Every time I attempt to make a post request, I keep receiving an error message stating that req.body is returning as undefined. Below is the content of my server.js file: import express from 'express'; import bodyParser from 'body-parser&ap ...

Creating distinctive identifiers for individual function parameters in JavaScript using addEventListener

I am working on a for loop that dynamically generates elements within a div. Each element should trigger the same function, but with a unique ID. for(var i = 0; i < 10; i++) { var p = document.createElement("p"); var t = document. ...

How does Vue handle the situation when the value of an input field does not match the bound "data"?

Before diving into the intricacies of v-model, I want to take a closer look at how v-bind behaves. Let's analyze the example below: <div id="app"> <input type="text" :value="inputtedValue" @input ...

Display the mobile keyboard without the presence of an input element

Attempting to display the mobile keyboard on my responsive site, I initially tried placing a hidden input with the placeholder "tap here." However, due to an event firing on this input that reloads the dom, I was unable to show the keyboard. I'm wond ...

Dynamic resizing in NextJs does not trigger a re-render

My goal is to dynamically pass the width value to a component's styles. Everything works fine on initial load, but when I resize the window, the component fails to re-render even though the hook is functioning as intended. I came across some informat ...

SSI stands for Server Side Includes, a feature that allows

I have multiple versions of the same HTML page, each with only one hidden variable that is different. This variable is crucial for tracking purposes. Now, I am exploring options to rewrite this by incorporating a HTML file with a hidden variable. Here is ...

Node.js and Express.js fails to transmit files to clients

Attempting to send a gif to the client for future use in CSS, but encountering a 404 error in the console log. The gif is located within the public directory. Server: var app = require('express')(); var http = require('http').Server(a ...