Combining property values based on a common property in an array of objects using JavaScript

I have a large array filled with various objects structured like:

[
        {
          "type": "bananas",
          "count": 15
        },
        {
          "type": "kiwis",
          "count": 20
        },
        {
          "type": "bananas",
          "count": 5
        },
        {
          "type": "strawberries",
          "count": 10
        },
        {
          "type": "strawberries",
          "count": 25
        }
]

My goal is to iterate through the array and combine counts for objects with matching types. Using the provided example, the desired output would be:

[
        {
          "type": "bananas",
          "count": 20
        },
        {
          "type": "kiwis",
          "count": 20
        },
        {
          "type": "strawberries",
          "count": 35
        },
]

If anyone has any tips or guidance on how to achieve this, I would really appreciate it.

Answer №1

One approach could be to utilize the reduce method, taking advantage of ES6 syntax.

let items = [
        {
          "type": "bananas",
          "quantity": 15
        },
        {
          "type": "grapes",
          "quantity": 25
        },
        {
          "type": "bananas",
          "quantity": 10
        },
        {
          "type": "apples",
          "quantity": 30
        },
        {
          "type": "apples",
          "quantity": 20
        }
]

let combinedItems = items.reduce((accumulator, currentValue) => {
  let existingItem = accumulator.find(item => item.type === currentValue.type);
  if (existingItem) {
    existingItem.quantity += currentValue.quantity;
  } else {
    accumulator.push(currentValue);
  }
  return accumulator;
},[])

console.log(combinedItems)

Answer №2

How about this code snippet to sum up counts for different types of fruits:

const fruitData = [
  {
    name: 'apples',
    quantity: 10
  },
  {
    name: 'oranges',
    quantity: 20
  },
  {
    name: 'apples',
    quantity: 5
  },
  {
    name: 'grapes',
    quantity: 20
  },
  {
    name: 'grapes',
    quantity: 10
  }
];

const fruitTypes = fruitData.map((fruit) => fruit.name);
const uniqueFruitTypes = [...new Set(fruitTypes)];

const totalQuantities = uniqueFruitTypes.map((fruitType) => ({
  name: fruitType,
  quantity: fruitData
    .filter((fruit) => fruit.name === fruitType)
    .map((fruit) => fruit.quantity)
    .reduce((acc, currQuantity) => acc + currQuantity, 0)
}));

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

What can I do to keep my navbar on top of the slideshow?

Is there a way to create a responsive navbar that sits in front of a slideshow containing images? I attempted to place the div within the main, but unfortunately it was unsuccessful. ...

Find the location in a node.js script where a promise was rejected

Recently, I encountered a code snippet from an npm package that has been causing me some trouble. The issue is that I'm having difficulty in pinpointing where the rejected promise is being created or rejected within node.js. const someHiddenEvil = fu ...

Unable to set a breakpoint within Angular constructor or OnInit method

I am currently facing an issue with my Angular application where breakpoints set in F12 tools in Chrome or IE are not working. I have a simple test case below: export class LoginComponent implements OnInit { message: string; constructor(private r ...

Class for Angular input validation when user doesn't enter text

When it comes to Angular forms, there are certain CSS input validation classes such as pristine, dirty, and invalid. One common issue arises when dealing with an input that has a minimum length requirement - we want to avoid displaying an error message in ...

Capturing screenshots with Selenium in Node.js is proving to be quite sluggish

My current project involves using Selenium with Mocha in Node.js for UI testing on a website. I want to capture screenshots after each test to review and share the results visually. The challenge arises when there are AJAX calls and JavaScript animations ...

Tips for converting the Instagram cURL post request to a JavaScript request

I am attempting to convert the code I received from Instagram into a token. The code provided in the Instagram DOCS uses a curl request, but I would like to implement it using JavaScript instead. Here is how the original code looks: curl -X POST &bsol ...

execute a function for every regex match found within a string

When working with WordPress or PHP in general, I came across this interesting recommendation for email obfuscation, and I would like to: Convert email addresses to mailto links Encode the mailto links using str_13() Decode them client-side using JavaScri ...

initiate a page refresh upon selecting a particular checkbox

So I've got this code that saves around 30 checkbox selections to local storage, which is working fine. Then there's this separate checkbox below, when checked it automatically reloads the page: <input type="checkbox" id="autoload" class="aut ...

An error occurred: The property 'toUpperCase' cannot be read of an undefined Observable in an uncaught TypeError

Encountering an issue during the development of a mobile app using the ionic framework for a movie application. After finding an example on Github, I attempted to integrate certain functions and designs into my project. The problem arises with the 'S ...

Discord bot struggling to reach every user in the server

After creating a discord bot with Discord.js, I was able to retrieve all the users from my server. However, lately I noticed that it is only returning 59 members out of the 300+ in total. I want to ensure that I am able to access all the users as before. ...

Arranging array elements according to the values in another array

I am working with an array of selections: var selections = ( JSON.stringify($('#approval').select2('data')) ); var selections = JSON.parse("[" + selections + "]"); When I use console.log with selections, the output is: https://i. ...

Dynamic image sources in reusable Gatsby-Image Component

Recently, I have been exploring Gatsby-Image for an upcoming project and have started experimenting with its capabilities. My test project was successful, but now I want to utilize the <Image /> tag from Gatsby in a similar way to a standard <img ...

"Why is the comparison function of bcryptjs returning null even though the hash being used is the one that was generated

For security purposes, I securely store hashed passwords in MongoDB. However, when I attempt to compare the stored password with a user-entered string, bcryptjs returns a null value. https://i.stack.imgur.com/4sTXM.png The hashed password is stored in bin ...

When transitioning from another page, the header will cover a portion of the section

I am facing a specific issue that I need help with. My goal is to have the navigation bar link to different sections of a single page when clicked. For example, clicking on "Contact" should take the user to the contact section, and then if they click on "A ...

Adjusting the border-right size based on scroll position

Apologies if this question seems trivial, but I am completely new to coding in HTML and JavaScript. I understand that I can make some changes based on scroll position, but right now I'm a little confused. I want to increase the height of a box as the ...

Using a JavaScript callback function as a parameter for the addJavascriptInterface method in Java

Can Java interact with arbitrary functional objects in JavaScript by calling them as callbacks? For example, if we have a function called 'access' that is registered to invoke a Java function: access(function(blabla){ ... }); Are there eff ...

Problem encountered while generating a torus shape using webGL

I am currently developing a program that aims to create 3D parametric shapes using webgl. The current code I have works successfully for rendering a sphere, but when I try switching the equations for a torus, only the upper half of the torus is being displ ...

How can I notify a particular user using Node.js?

This is the code I have for my server in the server.js file: var socket = require( 'socket.io' ); var express = require('express'); var app = express(); var server = require('http').createServer(app); var io = sock ...

Encountering undefined JavaScript functions when called from HTML

I had most of these functions working perfectly, but after restarting my program, I'm now encountering issues with undefined functions in Chrome. I can't pinpoint the exact problem, and even though I've checked through Eclipse, I still can&a ...

An error arises during the process of summing array elements with a "for loop"

Here is some code I am working on: String array[]=new String[5]; for(int i=0;i<array.length;i++){ array[i]= "item "+String.valueOf(i); i++; } After my application crashed, I received the following log message: java.lang.IndexO ...