Guide to iterating through an array of objects and calculating the total value of a particular property using Javascript

Given an array of objects containing battle information for Maria and Cristiano, the task is to scroll through them and add up their battlesWon count. Finally, display how many battles each one won as demonstrated in the example.

 const arrayOfBattles = [
      {
        id: '147acaa3-363c-4a28-af43-fcc035a1d500',
        arena: 'Philippine Arena',
        firstParticipant: {
          address: '0x3ba59bcc1a02cb46e7de35fb0bacc860bf075661',
          name: 'Cristiano',
          battlesWon: 0
        },
        secondParticipant: {
          address: '0x3ba59bcc1a02cb46e7de35fb0bacc860bf075644',
          name: 'Maria',
          battlesWon: 1
        },
        logs: [ [Object] ]
      },
      {
        id: 'b2ef2d28-d84d-4cc9-946f-3d57b8ce05ab',
        arena: 'Greensboro Coliseum',
        firstParticipant: {
          address: '0x3ba59bcc1a02cb46e7de35fb0bacc860bf075644',
          name: 'Maria',
          battlesWon: 1
        },
        secondParticipant: {
          address: '0x3ba59bcc1a02cb46e7de35fb0bacc860bf075661',
          name: 'Cristiano',
          battlesWon: 0
        },
        logs: [ [Object] ]
      }
    ]

Expected Output:

{
  Cristiano: 0,
  Maria: 2
}

Answer №1

One effective approach could involve iterating through the array using the forEach method, then storing the values in a results dictionary. This can be seen below:

let list = [
    {
        id: '147acaa3-363c-4a28-af43-fcc035a1d500',
        arena: 'Philippine Arena',
        firstParticipant: {
            address: '0x3ba59bcc1a02cb46e7de35fb0bacc860bf075661',
            name: 'Cristiano',
            battlesWon: 0
        },
        secondParticipant: {
            address: '0x3ba59bcc1a02cb46e7de35fb0bacc860bf075644',
            name: 'Maria',
            battlesWon: 1
        },
        logs: [[Object]]
    },
    {
        id: 'b2ef2d28-d84d-4cc9-946f-3d57b8ce05ab',
        arena: 'Greensboro Coliseum',
        firstParticipant: {
            address: '0x3ba59bcc1a02cb46e7de35fb0bacc860bf075644',
            name: 'Maria',
            battlesWon: 1
        },
        secondParticipant: {
            address: '0x3ba59bcc1a02cb46e7de35fb0bacc860bf075661',
            name: 'Cristiano',
            battlesWon: 0
        },
        logs: [[Object]]
    }
]

let results = {
    Cristiano: 0,
    Maria: 0
}

list.forEach(arena => {
    results[arena.firstParticipant.name] += arena.firstParticipant.battlesWon
    results[arena.secondParticipant.name] += arena.secondParticipant.battlesWon
})

console.log(results)

Answer №2

Utilizing Array.prototype.reduce enables you to iterate through each entry in the dataset and store participant data in the accumulator. This approach eliminates the need for creating an external object outside of your function.

Within each iteration of the reduce() method, a generic function is utilized to input participant data into the accumulator:

function handleParticipant(participant, acc) {
  const { name, battlesWon } = participant;
  acc[name] = (acc[name] || 0) + battlesWon;
}

The key logic lies in the line

acc[name] = (acc[name] || 0) + battlesWon
, which essentially means: if the given name exists in the dictionary, then add the value of battlesWon to it; otherwise, start with a base value of 0 and then add battlesWon.

Below is a proof-of-concept example:

const data = [
  {
    id: '147acaa3-363c-4a28-af43-fcc035a1d500',
    arena: 'Philippine Arena',
    firstParticipant: {
      address: '0x3ba59bcc1a02cb46e7de35fb0bacc860bf075661',
      name: 'Cristiano',
      battlesWon: 0
    },
    secondParticipant: {
      address: '0x3ba59bcc1a02cb46e7de35fb0bacc860bf075644',
      name: 'Maria',
      battlesWon: 1
    }
  },
  {
    id: 'b2ef2d28-d84d-4cc9-946f-3d57b8ce05ab',
    arena: 'Greensboro Coliseum',
    firstParticipant: {
      address: '0x3ba59bcc1a02cb46e7de35fb0bacc860bf075644',
      name: 'Maria',
      battlesWon: 1
    },
    secondParticipant: {
      address: '0x3ba59bcc1a02cb46e7de35fb0bacc860bf075661',
      name: 'Cristiano',
      battlesWon: 0
    }
  }
];

function handleParticipant(participant, acc) {
  const { name, battlesWon } = participant;
  acc[name] = (acc[name] || 0) + battlesWon;
}

const battlesWonByName = data.reduce((acc, cur) => {
  const { firstParticipant, secondParticipant } = cur;
  
  handleParticipant(firstParticipant, acc);
  handleParticipant(secondParticipant, acc);
  
  return acc;
}, {});

console.log(battlesWonByName);

Answer №3

Please proceed with the following code snippet.

const data = [
  {
    id: '147acaa3-363c-4a28-af43-fcc035a1d500',
    arena: 'Philippine Arena',
    firstParticipant: {
      address: '0x3ba59bcc1a02cb46e7de35fb0bacc860bf075661',
      name: 'Cristiano',
      battlesWon: 0
    },
    secondParticipant: {
      address: '0x3ba59bcc1a02cb46e7de35fb0bacc860bf075644',
      name: 'Maria',
      battlesWon: 1
    },
    logs: [ [Object] ]
  },
  {
    id: 'b2ef2d28-d84d-4cc9-946f-3d57b8ce05ab',
    arena: 'Greensboro Coliseum',
    firstParticipant: {
      address: '0x3ba59bcc1a02cb46e7de35fb0bacc860bf075644',
      name: 'Maria',
      battlesWon: 1
    },
    secondParticipant: {
      address: '0x3ba59bcc1a02cb46e7de35fb0bacc860bf075661',
      name: 'Cristiano',
      battlesWon: 0
    },
    logs: [ [Object] ]
  }
]

let resultData = {};

data.forEach(element => {
  ['firstParticipant', 'secondParticipant'].forEach(property => {
    if(resultData.hasOwnProperty(element[property]['name'])) {
      resultData[element[property]['name']] += element[property]['battlesWon'];
    } else {
      resultData[element[property]['name']] = element[property]['battlesWon'];
    }
  })
})

console.log(resultData);

Answer №4

Below is a way to achieve this:

const data = [
  {
    id: '147acaa3-363c-4a28-af43-fcc035a1d500',
    arena: 'Philippine Arena',
    firstParticipant: {
      address: '0x3ba59bcc1a02cb46e7de35fb0bacc860bf075661',
      name: 'Cristiano',
      battlesWon: 0
    },
    secondParticipant: {
      address: '0x3ba59bcc1a02cb46e7de35fb0bacc860bf075644',
      name: 'Maria',
      battlesWon: 1
    },
    logs: [ [Object] ]
  },
  {
    id: 'b2ef2d28-d84d-4cc9-946f-3d57b8ce05ab',
    arena: 'Greensboro Coliseum',
    firstParticipant: {
      address: '0x3ba59bcc1a02cb46e7de35fb0bacc860bf075644',
      name: 'Maria',
      battlesWon: 1
    },
    secondParticipant: {
      address: '0x3ba59bcc1a02cb46e7de35fb0bacc860bf075661',
      name: 'Cristiano',
      battlesWon: 0
    },
    logs: [ [Object] ]
  }
]

var updatedData = new Array();
data.map((battle) => {
    updatedData[battle.firstParticipant.name] = updatedData[battle.firstParticipant.name] != null ? battle.firstParticipant.battlesWon + updatedData[battle.firstParticipant.name] :  battle.firstParticipant.battlesWon;
    updatedData[battle.secondParticipant.name] = updatedData[battle.secondParticipant.name] != null ? battle.secondParticipant.battlesWon + updatedData[battle.secondParticipant.name] :  battle.secondParticipant.battlesWon;
});

Answer №5

One effective way to achieve the desired outcome is by utilizing the reduce function

arr.reduce((acc, curr) => {
  const { firstParticipant: { name: a, battlesWon: m }, secondParticipant: { name: b, battlesWon: n } } = curr;
  acc[a] = (acc[a] ?? 0) + m
  acc[b] = (acc[b] ?? 0) + n
  return acc;
}, {});

1)

const arr = [
  {
    id: "147acaa3-363c-4a28-af43-fcc035a1d500",
    arena: "Philippine Arena",
    firstParticipant: {
      address: "0x3ba59bcc1a02cb46e7de35fb0bacc860bf075661",
      name: "Cristiano",
      battlesWon: 0,
    },
    secondParticipant: {
      address: "0x3ba59bcc1a02cb46e7de35fb0bacc860bf075644",
      name: "Maria",
      battlesWon: 1,
    },
    logs: [[Object]],
  },
  {
    id: "b2ef2d28-d84d-4cc9-946f-3d57b8ce05ab",
    arena: "Greensboro Coliseum",
    firstParticipant: {
      address: "0x3ba59bcc1a02cb46e7de35fb0bacc860bf075644",
      name: "Maria",
      battlesWon: 1,
    },
    secondParticipant: {
      address: "0x3ba59bcc1a02cb46e7de35fb0bacc860bf075661",
      name: "Cristiano",
      battlesWon: 0,
    },
    logs: [[Object]],
  },
];

const result = arr.reduce((acc, curr) => {
  const {
    firstParticipant: { name: name1, battlesWon: battlesWon1 },
    secondParticipant: { name: name2, battlesWon: battlesWon2 },
  } = curr;

  acc[name1] ? (acc[name1] += battlesWon1) : (acc[name1] = battlesWon1);
  acc[name2] ? (acc[name2] += battlesWon2) : (acc[name2] = battlesWon2);

  return acc;
}, {});

console.log(result);

2)

const arr = [
  {
    id: "147acaa3-363c-4a28-af43-fcc035a1d500",
    arena: "Philippine Arena",
    firstParticipant: {
      address: "0x3ba59bcc1a02cb46e7de35fb0bacc860bf075661",
      name: "Cristiano",
      battlesWon: 0,
    },
    secondParticipant: {
      address: "0x3ba59bcc1a02cb46e7de35fb0bacc860bf075644",
      name: "Maria",
      battlesWon: 1,
    },
    logs: [[Object]],
  },
  {
    id: "b2ef2d28-d84d-4cc9-946f-3d57b8ce05ab",
    arena: "Greensboro Coliseum",
    firstParticipant: {
      address: "0x3ba59bcc1a02cb46e7de35fb0bacc860bf075644",
      name: "Maria",
      battlesWon: 1,
    },
    secondParticipant: {
      address: "0x3ba59bcc1a02cb46e7de35fb0bacc860bf075661",
      name: "Cristiano",
      battlesWon: 0,
    },
    logs: [[Object]],
  },
];

const result = arr.reduce((acc, { firstParticipant, secondParticipant }) => {
  acc[firstParticipant.name]
    ? (acc[firstParticipant.name] += firstParticipant.battlesWon)
    : (acc[firstParticipant.name] = firstParticipant.battlesWon);

  acc[secondParticipant.name]
    ? (acc[secondParticipant.name] += secondParticipant.battlesWon)
    : (acc[secondParticipant.name] = secondParticipant.battlesWon);
  return acc;
}, {});

console.log(result);

Answer №6

If you're working with nodeJs and need to verify an additional 'Johnn', this code snippet will come in handy.

This script uses lodash library to iterate through an array of objects containing participant data from different arenas.

import lodash  from 'lodash';
const participants = [
    {
        id: "147acaa3-363c-4a28-af43-fcc035a1d500",
        arena: "Philippine Arena",
        firstParticipant: {
            address: "0x3ba59bcc1a02cb46e7de35fb0bacc860bf075661",
            name: "Cristiano",
            battlesWon: 0,
        },
        secondParticipant: {
            address: "0x3ba59bcc1a02cb46e7de35fb0bacc860bf075644",
            name: "Maria",
            battlesWon: 1,
        },
        logs: [[Object]],
    },
    {
        id: "b2ef2d28-d84d-4cc9-946f-3d57b8ce05ab",
        arena: "Greensboro Coliseum",
        firstParticipant: {
            address: "0x3ba59bcc1a02cb46e7de35fb0bacc860bf075644",
            name: "John",
            battlesWon: 1,
        },
        secondParticipant: {
            address: "0x3ba59bcc1a02cb46e7de35fb0bacc860bf075661",
            name: "Cristiano",
            battlesWon: 0,
        },
        logs: [[Object]],
    },
];

const searchTerms = ['Cristiano', 'Maria', 'John'];
const attributesToSum = [{
    selector: 'firstParticipant.name',
    sum: 'firstParticipant.battlesWon'
},{
    selector: 'secondParticipant.name',
    sum: 'secondParticipant.battlesWon'
}];

function calculateTotalWins(participants, attributesToSum, searchTerms) {
    let result = {};
    participants.forEach((participantData) => {
        attributesToSum.forEach((attribute)=>{
            let index = searchTerms.indexOf(lodash.get(participantData, attribute.selector));
            let value = lodash.get(participantData, attribute.sum);
            if( index > -1) {
                result[searchTerms[index]] = result[searchTerms[index]] ? (result[searchTerms[index]] + value) : value;
            }
        });
    });
    return result;
}
console.log(calculateTotalWins(participants, attributesToSum, searchTerms));

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

Pass data in JSON format from Laravel controller to AngularJS

When working with Laravel, I successfully converted data in MySQL to JSON for use in AngularJS. However, I am now unsure of how to effectively utilize these values in AngularJS. Can anyone offer assistance? View output data (hide each value) https://i.ss ...

Prevent the instant spread in the AJAX success function

Here is a snippet of my code: $(document).on('click', '[data-submit-form]', function (event) { var form = $(this).closest('form'); $.ajax({ url : form.attr('action'), type : 'post' ...

Rephrase the ajax call and the data retrieved

I'm struggling to find a solution for writing this code snippet without using async: false,. var imageX; var groupX; $.ajax({ type:'GET', url:'php/myphp.php', dataType:'json', async: false, success: ...

What is the best way to categorize a collection of objects within a string based on their distinct properties?

I am working with an array of hundreds of objects in JavaScript, each object follows this structure : object1 = { objectClass : Car, parentClass : Vehicle, name : BMW } object2 = { objectClass : Bicycle, parentClass : Vehicle, name : Giant } object3 = { ob ...

Clearing a leaflet layer after a click event: Step-by-step guide

When working with my map, I attempt to toggle the layer's selection using a mouse click. Initially, my map looks like this: https://i.sstatic.net/lOI95.png Upon clicking a layer, my goal is to highlight and select it: https://i.sstatic.net/63Rx2.pn ...

Attempting to send multipart form data using Node.js Supertest

While experimenting with Node.js supertest to test a REST API script I wrote, I encountered an issue where I needed to mimic the following CURL request: curl -X POST -F api_key=KEY -F image=@my_file http://localhost:3000/v1/upload My initial attempt resu ...

steps for transferring a shallow copy of an array to a function

How can I adjust this code so that when I press each button, the console.log displays a different slice of the array instead of always showing me the last 20 elements? for (var i = 0; i < array.length; i++) { var b; var NewArr = []; ...

Is there a method to display a loading animation while the micro apps are being loaded in a single spa project?

Currently, I am working on a project using single spa and I need to implement a loader while my micro app is being loaded. Additionally, I also need the loader to be displayed when switching between these micro apps. Are there any methods to accomplish t ...

Passing a character array pointer to a function that takes a 2D character array as an argument

After some experimentation with a few lines of C code, I encountered an interesting problem. I defined a structure as follows: typedef struct menuScreen { char *lines[MENU_MAX_LINES]; }menuScreen; Next, I declared a 2D character array like this: stati ...

Utilizing ng-class within select alongside ng-options in Angular versions 1.4 and above

My issue is similar to the problem described in this post : How to use ng-class in select with ng-options I am looking to customize specific options in a select element using CSS. To illustrate, I have an array of people like so : var persons = [ {Name:& ...

Mapping an array of objects within another array of objects

I have a collection of objects that I looped through to extract the content: const teamSliderContent = [ { Description1: 'Chef. Mordy Wenk', Title: 'Head of the Chief staff.', id: 1, }, { Desc ...

Countdown to redirect or exit on Jquery mobile "pageshow" and "pagehide" events

Looking to implement a 30-second countdown on a Jquery Mobile page with specific requirements: (1) Countdown begins on pageshow (2) Redirects to new page when countdown expires (3) If user navigates away (pagehide) before countdown finishes, the timer fun ...

Interested in trying out Express and socket.io for chatting?

I've successfully set up the chat application, but now I'm faced with a dilemma: how can I make the chat work on the default port:80, where my main site is hosted? One solution that comes to mind is using an iframe - but is there another way? B ...

Error message: The property '__isVuelidateAsyncVm' cannot be read because it is undefined

I'm encountering an issue with the code I have in this codesandbox link. The code features a form with validation and a disabled "Calculate" button that should only become enabled when all fields are valid. However, I'm receiving the error messag ...

Turning a SUM / IF query with INNER JOIN in MySQL into a knex query

After successfully creating a MySQL statement for my project, I am now facing the challenge of translating it into a knex.js query builder. Unfortunately, I have not been able to find a straightforward solution in the knex.js documentation as there is no ...

Tips for modifying an axios instance during response interception

Is there a way to automatically update an axios instance with the latest token received in a response, without making a second request? The new token can be included in any response after any request, and I want to make sure that the last received token ...

Include scrollView on smaller screens based on conditions

While incorporating an overlay in my application, how can I integrate a ScrollView specifically for smaller devices? Initially, I am checking the width: const windowWidth = Dimensions.get("window").width; Subsequently, I am attempting to display the Scro ...

There seems to be an issue preventing the Chrome browser from launching with the error message: "ERROR: connect ECONNREFUSED 127.0

My setup includes: Operating System: Windows 10 (64 bit) Browser: Chrome version 58 Node.js: 6.10.1 Npm: 3.10.10 Chromedriver: 2.29.0 After running my tests with Chrome using Selenium standalone, I encountered an error in the console where Selenium was ...

Utilizing a filter within the ng-model directive

I have a question about using a filter with an h3 element. Here is the code snippet: {{ event.date | date:'dd-MM-yyyy' }} It's working perfectly fine and Angular is formatting the date as expected. However, when I try to use the same filte ...

Monitor a user's activity and restrict the use of multiple windows or tabs using a combination of PHP and

I am looking to create a system that restricts visitors to view only one webpage at a time, allowing only one browser window or tab to be open. To achieve this, I have utilized a session variable named "is_viewing". When set to true, access to additional ...