Merge similar elements in an array by a specific property

I am looking to create a new array that combines values of repeated campaigns

let arrayName = [
  { campaign: "a", value: 3 },
  { campaign: "b", value: 5 },
  { campaign: "c", value: 7 },
  { campaign: "a", value: 9 },
];

EXPECTED OUTPUT:

[
  { campaign: 'a', value: 12 },
  { campaign: 'b', value: 5 },
  { campaign: 'c', value: 7 }
]

Answer №1

To simplify an object, you can reduce the items it contains and then convert them back into objects.

const arrayName = [
  { category: "x", amount: 3 },
  { category: "y", amount: 5 },
  { category: "z", amount: 7 },
  { category: "x", amount: 9 },
];

const result = Object
  .entries(arrayName.reduce((acc, { category, amount }) =>
    ({ ...acc, [category]: (acc[category] || 0) + amount }), {}))
  .map(([category, amount]) => ({ category, amount }));

console.log(result);
.as-console-wrapper { top: 0; max-height: 100% !important; }

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

Creating an empty array inside a Python function is a straightforward task

I need help with a function that extracts a specific column of data from a parent array and stores it in a new blank array. I am unsure how to make the function create this new array for the extracted data. The function includes two variables, "title" and ...

At times, the loading image fails to appear on Ajax

Take a look at my code below: function apply_image_effect(){ $.ajax({ url: "image/image.php", global: false, type: "POST", data: ({my_color:encodeURIComponent($('#my_color').val()),my_size:$('#my_size&apos ...

Browserify Rails encountered an error - ParseError: Error with 'import' and 'export'. These statements can only appear with 'sourceType: module'

Recently, I encountered an issue while trying to integrate an NPM package into my Rails application. The problem I'm facing can be seen in the following image: https://i.stack.imgur.com/cIOw8.png I searched this forum for similar issues but found tha ...

Unable to retrieve values from a JSON decode file in Laravel

Scraped data from a website, stored it as a JSON file, and validated the JSON content. Now, I am looking to retrieve data from this file in Laravel. Below is a snippet of the JSON data. Can anyone assist me in resolving this issue? [{ "data" ...

Using AngularJS to prevent HTML injection in input fields

Is there an effective method to prevent HTML injection in input fields? As an example, if I have a search input field: <input id="search" type="text" ng-model="search" placeholder="search..."> I want to ensure that any attempts to input malicious c ...

Using Material-UI and React: Implementing a DatePicker within a Component instead of a Function

Could someone assist me in getting this code to function properly within React components? import React, { Fragment, useState } from "react"; import DateFnsUtils from "@date-io/date-fns"; // choose your lib import { DatePicker, MuiPickersUtilsProvider } f ...

Receiving a blank array from the firestore database

I have written a code for the LeftBar Component where I am trying to retrieve data stored in the "contacts" document in Firebase. However, I am getting an empty array and I'm not sure why this is happening. Additionally, I would like to know how to ac ...

When the 'keyup' event is detected, trigger the function only on keyup

Looking for assistance in setting this to only trigger on keyup events. Can anyone provide guidance? $(function() { $('#acf-field_5a32085c7df98-field_5a3208f87df99').on('keyup', function() { $('#link-headline-fb').text($( ...

Tips for avoiding simultaneous state transitions in Angular UI Router

My situation in my Angular application involves a frustrating issue. Whenever a user double-clicks quickly on a link to a specific state (ui-sref link), the target state starts loading twice. This would be manageable if the state window didn't freeze ...

What is the best way to obtain repetitive models for a particular brand in this scenario?

I am looking to display a specific subset of Chevrolet models in my code. Here is the snippet: <body ng-controller="marcasController"> <ul ng-repeat="marca in marcas"> <li ng-repeat="tipo in marca.modelo">{{tipo.nombre}}</li> ...

Approach to dividing PHP output into multiple outputs (AJAX, PHP) (nested AJAX requests, AJAX inside AJAX loop?)

Seeking advice on how to efficiently handle PHP output in small chunks for AJAX responseText. The project involves a webpage using AJAX to input a last name, which is then processed by a PHP program. The PHP code randomly selects three people with differen ...

I am unable to correctly fetch the data string using Jquery Ajax from the server

I have implemented a jQuery Ajax function to check the availability of a username in real-time from the database. If the username is not available, the response is marked as "Unavailable" and vice versa. While I am successfully receiving this response, I a ...

Tips on setting pre-defined data in a ReactJS form builder field

Currently, I am utilizing the reactjs-form-builder to create forms within a React.js environment. Below is an excerpt of my fields object: this.state = { id: null, loading: true, fields: { "fields&qu ...

Display arrays vertically within each column using PHP

I have an array with both rows and columns specified. My goal is to print each column as a list within a loop. $row = 3; $col = 4; $arr=[ '1' , '2' , '3' , '4', '5& ...

NextAuth: JWT callback that returns an object

I've been working on a project using Next.js (11.1.2) + NextAuth (^4.0.5) + Strapi(3.6.8). The Next Auth credentials provider is functioning correctly. However, I need to access certain user information using the session. I attempted to do this by ut ...

Updating Error: Unable to establish connection with IP address 104.16.21.35 on port 80; Error code: ECONNREFUSED. This issue is being handled by the _

I need help updating my Angular version from 5 to 6 and I'm following these steps: Want to upgrade project from Angular v5 to Angular v6 After running the commands ng update @angular/cli and ng update @angular/core, I encountered the err ...

Tips for saving all models retrieved using the `DB.find({})` method in Mongoose

Is it possible to edit values in an array of query results returned from the database? We know that we can use model.save() for a single Query/row, but what about multiple Query results in an array? How can we achieve this? Would something like the follo ...

When trying to invoke an Angular function from a JavaScript function, it is returning as undefined

When attempting to invoke an Angular function from a JavaScript function, I am encountering an issue where it is displaying as undefined. Below is an example demonstration I have created: import { Component, NgZone, OnInit } from '@angular/core&apo ...

Turn off automatic spelling correction and predictive text in a content-editable section

I'm currently working on a cross-browser application using Script#. I've incorporated a contenteditable div where users can input text. However, I am facing an issue with the auto correct/auto completion feature altering the user's text. Co ...

Managing State in React: A Guide to Updating Child Component State from Parent Component

I'm still fairly new to working with React and I'm trying to implement a Bootstrap modal for displaying alert messages. Within my main App.js file, I have an error handler that sends a prop to a Modal.js component in order to trigger the modal t ...