Is there a way to add up values within a reduce function using multiple conditions?

Is there a way to sum up data based on specific conditions within a reduce function? Let's consider the following dataset:

const data = [
{
   "id": 1,
   "option": "BP",
   "result": 'win',
   "amount": 50
},
{
   "id": 3,
   "option": "BP",
   "result": 'win',
   "amount": 20
},
{
   "id": 5,
   "option": "VN",
   "result": 'win',
   "amount": 50
},
{
   "id": 5,
   "option": "GB",
   "result": 'loss',
   "amount": 40
}
];

Let's explore how we can achieve this using a code snippet:

data.reduce((total, item) => {
      if (
        item.option === 'VN'
              && item.result === 'win'
      ) {
        total += item.amount;
      }
      return total;
    }, 0);

While this code sums up specific data according to a set condition, what if we want to calculate totals for different options and results without repeating the code? How can we modify the reduce function to achieve the desired result?

{
  TotalBPWin: 70,
  TotalVN: 50,
  TotalGBLoss: 40
}

Answer №1

To calculate the total wins and losses for different options, use the reduce method by passing an object with keys TotalBPWin, TotalVN, and TotalGBLoss, all initialized to 0. Then, based on certain conditions, incrementally add the amounts together.

const data = [{
    id: 1,
    option: "BP",
    result: "win",
    amount: 50,
  },
  {
    id: 3,
    option: "BP",
    result: "win",
    amount: 20,
  },
  {
    id: 5,
    option: "VN",
    result: "win",
    amount: 50,
  },
  {
    id: 5,
    option: "GB",
    result: "loss",
    amount: 40,
  },
];

const accumulator = {
  TotalBPWin: 0,
  TotalVN: 0,
  TotalGBLoss: 0,
};

const result = data.reduce((newValueBetting, { option, result, amount }) => {
  if (option === "VN" && result === "win") {
    newValueBetting["TotalVN"] += amount;
  } else if (option === "BP" && result === "win") {
    newValueBetting["TotalBPWin"] += amount;
  } else if (option === "GB" && result === "loss") {
    newValueBetting["TotalGBLoss"] += amount;
  }
  return newValueBetting;
}, accumulator);
console.log(result);

Answer №2

Instead of starting with 0, the approach here is to utilize objects in the reduce function. The code snippet showcases a basic implementation, but you might want to adjust the condition within the reduce method for accurate summation.

const data = [
{
   "id": 1,
   "option": 'BP',
   "result": 'win',
   "amount": 50
},
{
   "id": 3,
   "option": 'BP',
   "result": 'win',
   "amount": 20
},
{
   "id": 5,
   "option":'VN',
   "result": 'win',
   "amount": 50
},
{
   "id": 5,
   "option":'GB',
   "result": 'loss',
   "amount": 40
}
];

let result = {
  'VN':0,
  'GB':0,
  'BP':0
};

data.reduce((acc,item) => {

  result[item.option] += item.amount

  return acc;
}, result);

console.log(result)

Answer №3

By utilizing the reduce method, you can calculate the total sum of counts for each option. It is important to note that if an option has zero wins, there will not be a corresponding sum displayed (refer to the log output).

const data = [{id:1,option:"BP",result:"win",amount:50},{id:3,option:"BP",result:"win",amount:20},{id:5,option:"VN",result:"win",amount:50},{id:5,option:"GB",result:"loss",amount:40}];

const result = data.reduce((all, el) => {
  if (el.result === "win") {
    all[el.option] = (all[el.option] || 0) + el.amount; 
  }
  return all;
}, {});

console.log(result.BP);
console.log(result.VN);
console.log(result.GB);

Answer №4

All you need is a straightforward loop to accomplish this task without any requirement for using if() statements.

const team=[{id:1,player:"CT",score:"100"},{id:3,player:"CLT",score:"250"},{id:5,player:"BC",score:"400"},{id:5,player:"RCB",score:"-50"}];

const results= {};

team.forEach(entry=>{
   const key = 'Total' + entry.player + entry.score
   results[key] = (results[key] || 0) + entry.amount
});

console.log(results)

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

JavaScript/jQuery: What is the best way to assign an element as the context ('this') of a function?

Is there a way to pass something to a function and have it act as if it's calling the function itself? Consider this function: function ShowId() { alert($(this).attr('id')); } and this block of HTML: <div id='div1'> & ...

Authenticating with Google using a Custom Application Title

My website currently requires Google+ authentication in the following way - However, I want to revamp it to resemble stack overflow's method - Here are two necessary changes - 1) Replace This app with My App Name 2) Include only View your email ad ...

Are asynchronous promises thenable for chaining?

Can someone explain to me how asynchronous chaining works with thenable? I am new to using promises in Node.js and I am a bit confused about the concept. In the code example provided below, it seems like the promise returned from the previous Promise.the ...

Issue with column-break-before toggle function only operational in Safari

In my website layout, I have arranged li elements in a 2 column design. I am looking to implement a specific functionality where if a div element (inside an li element) is clicked, it should add a class with the following CSS properties: -webkit-column-br ...

Use CSS to position the SVG element to the bottom right corner of the screen

I have a <div> on the page with the CSS class .svgImage applied to it. Whenever I resize the browser window, the svg image resizes correctly but keeps shifting its position on the page. When I make the browser window vertically smaller, the svg imag ...

Encountering difficulty in assigning the desired value to the select box

// updating the subType value in the controller $scope.newEngagement.subType = 3; // creating a list of engagement subTypes $scope.engagementSubTypeList = [ { "subTypeId": 1, "subTypeName": "value1" }, { "subTypeId": 2, "subTypeName": "value2" }, { " ...

Ways to align the label at the center of an MUI Textfield

My goal is to center the label and helper text in the middle of the Textfield. I managed to achieve this by adding padding to MuiInputLabel-root, but it's not responsive on different screen sizes (the Textfield changes size and the label loses its cen ...

Error: The function `map` cannot be applied to the components

My issue involves using the same components in two different locations, where one isn't functioning properly. The error is occurring in Board.js: TypeError: components.map is not a function const Board = () => { const [components, ...

Having trouble signing into Xbox One after upgrading Unity package to version 1707 QFE 1 Release

My game was successfully published and I could sign in using the 1705.4 package. However, after updating to version 1707 QFE 1, the sign-in feature stopped working. All I did was drag and drop the prefab onto the scene. While in Unity, the sign-in function ...

Unable to get md-virtual-repeat to work within md-select?

Attempting to use md-select to showcase a large amount of data is causing the browser to freeze upon opening. To address this, I tried implementing md-virtual repeat within md-select for improved performance. However, the code doesn't seem to be funct ...

Is there a different method I can utilize to create a conditional statement for assigning a value in JavaScript?

I have this code snippet that seems a bit unclear to me: if (!app.config.admin.examStatusId) { app.config.admin.examStatusId = exam.examStatus.dataPlus[0].id; } Do you have any suggestions on how I could rewrite this more clearly without using an if s ...

Inconsistent behavior between Chrome and Firefox when using AngularJS $resource GET method: success in Chrome but error

I am currently working on a simple custom GET request in Angular using $resource angular.module('myApp') .factory('MyService', function($resource){ return $resrouce('some url', {}, { list: {method:'G ...

Three.js: Apply a single color to a mesh shaderMaterial until a specific point is reached

I am struggling to grasp the concept of Three.js shaders. My goal is to apply a color to a mesh, but only up to a specific point. Here is my progress so far. I want the green color to "stop" at 50% of the mesh height For the remaining part of the mesh (ab ...

The mobile display is crowded with stacked cards

Everything was going smoothly with the three cards I created, but when viewed on mobile devices they end up stacking on top of each other. This is not the result I had anticipated after importing all the necessary jQuery and CSS files. <link rel="sty ...

The 'v-model' directive is unable to modify the iteration variable directly

I recently came across an interesting article about Renderless Components, which discuss splitting a component into a presentational (view) part and a renderless (logical) part using the $scopedSlots property. The concept was demonstrated with a simple Tag ...

Having trouble populating the container with page content using AJAX, PHP, and JS?

Whenever I attempt to use the buttons to change the content, I keep receiving a 'There is no such page!' message. Below is the index.html: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1- ...

Managing PHP Arrays in Ajax Responses

When making an AJAX request to a PHP file, I use the following code: $.post({ url: "manage.php", dataType: "JSON" }, { firtname: John, lastname: edwin }, function(data){ $("#persons").html(data[0]) }); The PHP file then returns data ...

ng2-idle server side rendering problem - Uncaught ReferenceError: document is undefined

Can ng2-idle be used for idle timeout/keepalive with pre-rendering in Angular 4? I followed this link for implementation: It works fine without server pre-rendering, but when I add rendering back to my index.html, I keep getting the following error: Exce ...

Tips for performing a redirect in JavaScript/ReactJS without storing the redirection in the cache

In my TypeScript ReactJS SSR App, I have the following logic: public login() { let error: boolean = false const isLoggedIn: boolean = doSomeLogicHereLikeBackendCheck() if(isLoggedIn) { window.location.href = "/home" // this is getting c ...

What is causing the ESLint error when trying to use an async function that returns a Promise?

In my Next.js application, I have defined an async function with Promise return and used it as an event handler for an HTML anchor element. However, when I try to run my code, ESLint throws the following error: "Promise-returning function provided t ...