Skip to content
Advertisement

Calculating difference between 2 items in JavaScript object

I have some customer data in an array of javascript objects that looks as such:

JavaScript

I would like to loop over and get the difference between food_cost and prev_year_food_cost for each client. So ideally, I would have a new object containing client, food_cost and the difference.

JavaScript

I have tried this but its not quite right. It’s pseudo code.

JavaScript

Advertisement

Answer

You can use Array#map to apply the transformation over each object, using Math.abs to find the absolute difference.

We can use destructuring to remove the prev_year_food_cost from the object.

This can be made more configurable by using the bracket syntax:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement