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

Error: Property 'onclick' cannot be set on a null object

JavaScript isn't my strong suit, so I'm struggling to solve this issue. The console is showing me the following error message: Uncaught TypeError: Cannot set property 'onclick' of null <script> var modal = document.getE ...

Tips for canceling an http request in angularjs when the requesting controller has exited its scope

Developed a custom angularjs application with ng-view for loading four different modules using route provider. Each module makes HTTP requests as shown below: var requestManager = { "locations": {}, "employees": {}, "items": {}, "templates ...

Displaying JavaScript Countdown in PHP Table

I have a database table with multiple fields and I am looking to create a countdown using the integer value from one of the fields (in minutes). How can I loop through and display the countdown for each row in a PHP table utilizing these values, with the a ...

Iterating over objects within a nested array using ng-repeat

My back-end is sending me an array of string arrays (Java - CXF-RS). The length of each array within the string arrays ranges from 1 to n. In order to display this data on my front-end, I am utilizing ng-repeat. Everything is functioning correctly with o ...

Adding a cell break line within AG-GRID in an Angular application

I'm trying to display two sets of data in a single cell with ag-grid, but I want the data to be on separate lines like this instead: Data with break line I attempted to use "\n", "\r", and "\br" but it didn't work. Here is my code ...

When embedding HTML inside an Angular 2 component, it does not render properly

Currently, I am utilizing a service to dynamically alter the content within my header based on the specific page being visited. However, I have encountered an issue where any HTML code placed within my component does not render in the browser as expected ( ...

How do I navigate to a different page in Vue.js HTML based on user selection?

Here is my first attempt at writing HTML code: <div class="col-md-4" > <div class="form-group label-floating"> <label class="control-label">Select No</label> <select class="form-control" v-model="or" required=""> ...

Having trouble with the image compressor not being imported correctly in Next.js?

I've been attempting to compress an image, but when I try to import the ImageCompressor normally like this: import ImageCompressor from "image-compressor.js"; It throws an error: Uncaught ReferenceError: window is not defined This is the s ...

Issues encountered with the v-model functionality in a Laravel and Vue.js integrated to-do list

Recently, I created a to-do list application using Laravel and Vue.js. The concept is simple: users can add categories and within each category, they can create a list of tasks or to-dos. However, I encountered a minor issue with the input fields - whateve ...

How can I use jQuery to switch the positions of two <div> elements in HTML based on the selection of a dropdown value?

I need to switch the display positions of two <div> containers based on a dropdown value change. Can this be accomplished using jQuery? Here are the two div containers whose display positions need to be interchanged: <div id="first"><p> ...

What is the best way to implement an AppBar that fades in and out when scrolling within a div?

I'm trying to implement a Scrollable AppBar that hides on scroll down and reappears when scrolling up. Check out this image for reference To achieve this functionality, I am following the guidelines provided by Material-UI documentation export defa ...

How can I ensure that all row checkboxes are automatically marked as checked upon loading the Material Table in ReactJS?

I'm currently working on a project using React Material Table and I need to have the selection option pre-checked by default. Is there a way to accomplish this? function BasicSelection() { return ( <MaterialTable title="Basic Selec ...

Tips for passing arguments to event handlers in React JS

While going through the React JS documentation, I came across the concept of "Lifting State Up" and I have some confusion about it. You can check out the codepen sample here: https://codepen.io/valscion/pen/jBNjja?editors=0010 In the TemperatureInput comp ...

What is the best method for retrieving multiple json_encode PHP outputs through Ajax?

$errMsgUsername=""; $errMsgPassword=""; if ($_POST['username']==""){ $errMsgUsername="Username is null"; } if ($_POST['password']==""){ $errMsgPassword="Password is null"; } echo json_encode(['er ...

Troubleshooting issue with DOM not refreshing after making a $http POST request in a MEAN

I am working on an app that interacts with a Mongo database through CRUD operations. Currently, I have a form input where users can add elements, and I want these elements to appear below the form in real-time as they are added. However, at the moment, the ...

Elevate javascript

How can I create a new constructor that will alert the increment value? Any suggestions on how to achieve this? This is the current code snippet: var increment = new Increment(); alert(increment); /* 1 */ alert(increment); /* 2 */ alert(increment + incr ...

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: ...

Unexpected results occur when accessing data in $uibModal.open() within Angular JS causing it to

Here is the code snippet that is causing the issue of returning undefined items in AngularJS: App.js code console.log('single page application script is working'); var myApp = angular.module("demoApp", ["ngRoute", 'ui.bootstrap',&apos ...

Setting up node.js for angular - serving static files with connect.static and running unit tests

Currently, I am in the process of setting up a basic node webserver by following a tutorial outlined in Pro AngularJS published by Apress. Node.js along with both the connect and karma modules have been successfully installed on my system. During the ins ...

Hover over to disable inline styling and restore default appearance

There are some unique elements (.worker) with inline styles that are dynamically generated through Perl. I want to change the background when hovering over them and then revert back to the original Perl-generated style. The only way to override the inline ...