Adding property values based on another property in JavaScript

My current object looks something like this:

[
  {
    origin: "XX",
    destination: "YY",
    volume: 500
  },
  {
    origin: "ZZ",
    destination: "YY",
    volume: 500
  }
]

I am looking to use map and reduce functions to sum up the volumes based on a specific property, in this case, the destination.

The desired output should be:

 [
   {
     destination: "YY",
     volume: 1000
   }
]

Appreciate your help with this, thank you.

Answer №1

When attempting to group the array based on the destination property, you can utilize a versatile groupBy function in TypeScript. This function constructs a Map (compatible with ES2015 or newer) mapping destination values to arrays of objects sharing that specific value for destination:

function groupBy<T, K extends keyof T>(key: K, arr: T[]): Map<T[K], T[]> {
  const map = new Map<T[K], T[]>();
  arr.forEach(t => {
    if (!map.has(t[key])) {
      map.set(t[key], []);
    }
    map.get(t[key])!.push(t);
  })
  return map;
}

Next, taking into consideration your provided input:

const input = [
  {
    origin: "XX",
    destination: "YY",
    volume: 500
  },
  {
    origin: "ZZ",
    destination: "YY",
    volume: 500
  }
]

You can transform the array entries from the grouped Map into an array of objects that contains the grouped destination and calculates the sum of volume for each specified group:

const output = Array.from(groupBy("destination", input).entries())
  .map(([dest, objs]) => ({
    destination: dest,
    volume: objs.reduce((acc, cur) => acc + cur.volume, 0)
  }))

console.log(JSON.stringify(output)); // generates the desired result

May this solution assist you in your endeavors! Best of luck!


I have successfully tested this code snippet in the TypeScript Playground using v2.5.1 as per the current date. Feel free to explore it further by visiting here.

Answer №2

Give this a shot:

var data = [{
    origin: "AA",
    destination: "BB",
    volume: 300
  },
  {
    origin: "CC",
    destination: "BB",
    volume: 600
  }
];

function totalVolume(arr, propType, propVal) {
  var sum = 0;
  arr.forEach(function(item) {
    if (item[propType] && item[propType] === propVal) {
      sum += item.volume;
    }
  });
  console.log({
    [propType]: propVal,
    volume: sum
  });
}

totalVolume(data, "destination", "BB");

Answer №3

By utilizing the power of Array.reduce, it is possible to create a universal collector method that is independent of any specific data structure. This method relies on the first collector or accumulator argument to handle data structure-specific getter and setter functions necessary for manipulating the data.

To properly execute the provided example code, an implementation may resemble the following...

var dataList = [{
    origin: "XX",
    destination: "YY",
    volume: 500
}, {
    origin: "ZZ",
    destination: "YY",
    volume: 500
}, {
    origin: "XX",
    destination: "AA",
    volume: 200
}, {
    origin: "ZZ",
    destination: "AA",
    volume: 100
}];

function collectSourceValueConnectedTargetSummaries(collector, dataItem) {
    var registry = collector.registry;
    var sourceValue = collector.getSourceValue(dataItem);
    var summaryItem = registry[sourceValue];

    if (!summaryItem) {
        summaryItem = registry[sourceValue] = Object.assign({}, collector.summaryItem);

        collector.putSummarySource(summaryItem, sourceValue);
        collector.summaryList.push(summaryItem);
    }
    collector.summarizeTarget(summaryItem, collector.getTargetValue(dataItem));

    return collector;
}

var result = dataList.reduce(collectSourceValueConnectedTargetSummaries, {
    registry: {},
    getSourceValue: function(dataItem) { return dataItem.destination },
    getTargetValue: function(dataItem) { return dataItem.volume },
    putSummarySource: function(summaryItem, value) { summaryItem.destination = value; },
    summarizeTarget: function(summaryItem, value) { summaryItem.volume = (summaryItem.volume + value); },
    summaryItem: {volume: 0},
    summaryList: []
}).summaryList;

console.log('dataList : ', dataList);
console.log('reduced dataList / result : ', result);
.as-console-wrapper { max-height: 100%!important; top: 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

Issue with create-react-app and express server not displaying correctly in Internet Explorer

My application functions perfectly with Chrome and Safari. It utilizes React for the front-end and Express for the back-end. However, when I try to open it in Internet Explorer, all I see is a blank white page. Additionally, I encounter this error message: ...

Using JavaScript to execute a PHP function for updating or inserting data into an SQL database

I seem to be facing some minor issues at the moment. I have this JavaScript function that updates the stream of the VLC web plugin. However, what I am really trying to do is incorporate a way to input data into my database to keep track of how many viewers ...

How can I incorporate a fade opacity effect into my Div scrolling feature?

I successfully implemented code to make div elements stick at the top with a 64px offset when scrolling. Now, I am trying to also make the opacity of these divs fade to 0 as they scroll. I am struggling to figure out how to achieve this effect. Below is ...

Is it possible to set a different default page index other than 0 in a material table using reactjs?

I have noticed that the default page index in the material table is set to '0', but the API I am currently using begins with a page index of '1'. Is there a way to adjust the default page index of the table to match that of the API? ...

Eliminating bottom section in HTML/CSS

I've got this code snippet: new WOW().init(); /* AUTHOR LINK */ $('.about-me-img img, .authorWindowWrapper').hover(function() { $('.authorWindowWrapper').stop().fadeIn('fast').find('p').addClass('tr ...

Error: Unable to locate module: cannot find './node_modules/@material-ui/core/IconButton'

Encountering an error in the browser: Error: Failed to compile ./src/components/layout/search/Searchbar.js Module not found: Can't resolve './node_modules/@material-ui/core/IconButton' in 'C:\Users\Ja\Desktop\ ...

Using TypeScript with CanvasJS

While working on my TypeScript project, I encountered an issue with integrating CanvasJS using the declaration file - index.d.ts. The corresponding JavaScript file can be found at . I am utilizing require.js in my project, but it crashes when running beca ...

Insufficient attributes in TypeScript component for React application

Developing with React import {Input} from '@xxx/forms'; <Input label="account Name" name="account"/> Type Definition for input import React, { Ref } from 'react'; import { InputProps as UITKInputProps } from ...

Express Node.js Error: Address Information Syntax Issue

While developing my server using TypeScript for my Angular app to connect to, I encountered an issue when trying to run the code snippet below. It seems that Node.js or TS is not yet compatible with certain ES6 features like destructuring with AddressInfo, ...

Node.js VAR DeclarationIn the world of Node.js, we make

I am currently expanding my knowledge on Node.js. I came across a line in my book that has sparked my curiosity, and I wanted to seek some clarification. The specific line in question is: var user = req.user = users[req.params.name]; After doing some re ...

Error encountered: "Unable to locate module 'typescript-Collections' when modifying the module to "umd" or "amd" in the tsconfig.json file."

I recently upgraded to VS17 Enterprise and encountered an issue when trying to import the TypeScript Collections library from GitHub. After following the instructions on their page, I realized that changing the module option in my tsconfig.json file to eit ...

AngularJS: Implementing WebSocket Reconnection Logic within a Service

Utilizing web sockets within my AngularJS application has been a great addition. However, I encountered an issue where the web socket connection closes when a user logs out. Upon the user logging back in, I need to reconnect the web socket. The current ...

What is the reason for converting arrays to strings when making requests, but not objects?

Yesterday evening, while using AJAX to send data to my server through $.post, I encountered a problem where JavaScript Arrays had to be "stringified" and added as a field to an object before being transmitted. Here's what the code looked like: $.post ...

Accessing HTML partials from separate domains using AngularJS

I am looking to load html partials from Amazon S3 by uploading them and using the public URLs like this: 'use strict'; /* App Module */ var phonecatApp = angular.module('phonecatApp', [ 'ngRoute', 'phonecatAnimatio ...

Experiencing "localhost redirect loop due to NextJS Middleware" error

After successfully integrating email/password authentication to my locally hosted NextJS app using NextAuth, I encountered an issue with the middleware I created to secure routes. Every time I tried to sign out, I received an error stating "localhost redir ...

Error: The code is trying to access the property 'string' of an undefined variable. To fix this issue, make sure to

I encountered an issue after installing the https://github.com/yuanyan/boron library. The error message I received is: TypeError: Cannot read property 'string' of undefined Error details: push../node_modules/boron/modalFactory.js.module.expor ...

Combining JSON and JavaScript for embedding a SPARQL query into an HTML document

I have successfully implemented an HTML + SPARQL + JSON + JavaScript program, which can be viewed here: Below is the code snippet for the SPARQL + JSON + JavaScript: function retrieveData() { var query = "PREFIX : <http://dbpedia.org/resource/> P ...

Leveraging x-template in VueJS to create a sub-component within a larger component

I'm having trouble understanding how to properly use x-template for a subcomponent within a VueJS component. My component, CategoryNav.vue, has a template that uses an x-template to display a list. However, when I render the page, the component creat ...

Retrieve information from XML using jQuery

<?xml version="1.0" encoding="UTF-8"?> <slider> <csliderData1> <title>Kung Fu Panda</title> <content>In the Valley of Peace, Po the Panda finds himself chosen as the Dragon Warrior despite</content ...

Breadcrumb navigation that is determined by data hierarchies and relationships between parent and child items

I am looking to implement a dynamic breadcrumb system on my website using data-driven methodology. The necessary data is stored in a MariaDB database and has the following structure: parent_id | parent_name | child_id | child_name ——————— ...