Aggregate the properties of objects in an array into a single object using Lodash

I've been struggling to figure this out on my own, so I decided to seek advice from those with more experience. I have an array of objects called items, and I need to sum up specific properties across different objects in the array. The user can select certain properties, and I need to only sum those up based on their selections. My initial thought was to use the _.pick function in lodash for this task. Ideally, I would like to accomplish this in just one loop since the items array could potentially contain up to a thousand items. Here's an example:

var items = [
{'lightBlue':4, 'darkBlue':2, 'red':4, 'orange':6, 'purple':7},
{'lightBlue':6, 'darkBlue':5, 'red':1, 'orange':2, 'purple':3},
{'lightBlue':2, 'darkBlue':4, 'red':3, 'orange':4, 'purple':9}
]

var userSelectedColors = ['lightBlue', 'darkBlue'];

The desired output is the summation of all selected colors (in this case, blue):

var summedUp = [{'lightBlue':12, 'darkBlue':11}];

Finally, adding up these results gives us the total count:

var totalCount = 23;

What is the most efficient way to achieve this using lodash? Keep in mind that the userSelectedColors array could have any combination of colors chosen.

Please provide an example. Any help or suggestions are greatly appreciated!

Answer №1

Try using the _.sumBy method.

var total = _.sumBy(selectedColors, _.partial(_.sumBy, items));

var items = [
  { 'lightBlue': 4, 'darkBlue': 2, 'red': 4, 'orange': 6, 'purple': 7 },
  { 'lightBlue': 6, 'darkBlue': 5, 'red': 1, 'orange': 2, 'purple': 3 },
  { 'lightBlue': 2, 'darkBlue': 4, 'red': 3, 'orange': 4, 'purple': 9 }
], selectedColors = ['lightBlue', 'darkBlue'];

var total = _.sumBy(selectedColors, _.partial(_.sumBy, items));

console.log(total);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>

If we expand on that code:

var total = _.sumBy(selectedColors, function(color) {
    return _.sumBy(items, color);
});

For a more efficient solution without Lodash, you can consider this approach:

var total = items.reduce(function(acc, obj) {
    return acc + selectedColors.reduce(function(sum, color) {
        return sum + obj[color];
    }, 0);
}, 0);

var items = [
  { 'lightBlue': 4, 'darkBlue': 2, 'red': 4, 'orange': 6, 'purple': 7 },
  { 'lightBlue': 6, 'darkBlue': 5, 'red': 1, 'orange': 2, 'purple': 3 },
  { 'lightBlue': 2, 'darkBlue': 4, 'red': 3, 'orange': 4, 'purple': 9 }
], selectedColors = ['lightBlue', 'darkBlue'];

var total = items.reduce(function(acc, obj) {
    return acc + selectedColors.reduce(function(sum, color) {
        return sum + obj[color];
    }, 0);
}, 0);

console.log(total);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>

Answer №2

When it comes to efficiency, this method stands out as it only makes a single iteration through the array. However, its approach may not be as concise as @4castle's. (Notably, for arrays containing just 1000 items, any performance disparity would likely go unnoticed anyway.)

var items = [
    {'lightBlue':4, 'darkBlue':2, 'red':4, 'orange':6, 'purple':7},
    {'lightBlue':6, 'darkBlue':5, 'red':1, 'orange':2, 'purple':3},
    {'lightBlue':2, 'darkBlue':4, 'red':3, 'orange':4, 'purple':9}
]

var userSelectedColors = ['lightBlue', 'darkBlue'];

var sums = {};

_.each(items, function (item) {
    _.each(userSelectedColors, function (color) {
        sums[color] = (sums[color] || 0) + item[color];
    });
});

console.log('Summary: ', sums);

console.log('Grand total: ', _.sum(_.values(sums)));

Output:

Summary:  { lightBlue: 12, darkBlue: 11 }
Grand total:  23

Answer №3

Summarizing Selected Colors

const colorSummary = userSelectedColors.map(color => ({ [color]: _.sumBy(items, color)}))

Overall Count

const totalColorCount = _.sum(Object.values(colorSummary))

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 is the best way to animate an element when it comes into the user's view

In order to activate the animation of the skill-bars when the element is displayed on the website, I am seeking a solution where scrolling down through the section triggers the animation. Although I have managed to conceptualize and implement the idea with ...

Ways to utilize jquery to limit the length of an editable div and prevent it from exceeding our specified restriction

Imagine a scenario where you have the following code snippet: <div id="editing" contenteditable onclick="document.execCommand('selectAll',false,null)">Put text here...</div> In this situation, let's say you want to impose a r ...

Error encountered: Segmentation fault occurred following minor adjustments to my code

Let me highlight the key sections: (Declaration) typedef struct { /* for an entry in the position table */ int r; int c; } pos; pos *p_opo[9]; (in main) for (i = 0; i < count; i++) { p_opo[i] = (pos *) calloc(row_num * col_num / ...

When attempting to retrieve the data from a JSON file using an XMLHttpRequest, the result that is returned is [object object]

I am currently studying JSON and found a helpful guide on w3schools. Here is the code provided in the guide: https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax The guide also includes a sample JSON file: https://www.w3schools.com/js/json_demo.t ...

Instead of using a checkmark, consider using step numbers with Mui Stepper's Completed StepIcon

I'm currently utilizing Mui Stepper from [email protected] within a React project. Despite my efforts to search on platforms like Stackoverflow and Github, I have been unable to find a solution for displaying the step number upon completion inst ...

Why are my basic style properties not appearing correctly when I use json_encode on an array?

My calendar is written in Javascript within a table with the ID "calendario," allowing me to manipulate it using calendario.rows[i].cells[i]. This calendar lets users make reservations and provides an option to close a day if there are too many reservatio ...

What is the process for generating a new array of objects by leveraging the contents of two given arrays?

In my data collection, I have multiple objects stored in arrays like so: tableCols = [ { "id": 50883, "header": "ABC", "operator": "Sum", "order": 2 }, ...

Creating a responsive image within a panel using Bootstrap

I've been struggling to make a responsive image fit inside a panel while maintaining its aspect ratio and ensuring none of it gets cut off. I've attempted various CSS tweaks with no success. My setup involves Bootstrap along with React.js using r ...

Brother or sister is never empty, as every comment is considered an entity

When going through a list of jQuery objects, I want to verify if the nextSibling attribute is null. However, I found that an HTML comment also counts as a sibling object. How can I address this issue? I am looking for an if statement that will trigger fo ...

Location of Custom HTML Widget in Django-Dashing

I've encountered a dilemma while using the Django-Dashing framework, specifically regarding the placement of my HTML file for a custom widget. I have meticulously configured the code in my dashboard.html file to ensure proper loading. {% extends &apo ...

Getting a result from a Node.js function that includes a database query

Currently, I am diving into the world of Node.js and delving into working with MySQL connections. There is a particular function that should retrieve a set of rows from the database successfully. However, after retrieving these rows, I am unsure of how to ...

Debugging Typescript code with line numbers

When opening the console in a browser, typically the javascript line number of a function call or error message is displayed. However, my current setup involves using TypeScript, which gets compiled to Javascript. I am wondering if there is a way to retr ...

Unable to load dynamic data in Angular 2 smart table

Currently, I am utilizing Angular 6 along with smart table by visiting this link: . Everything was functioning smoothly, until the moment I attempted to switch from static to dynamic data: The following code works perfectly and displays all the content ...

I am encountering an issue stating "indexRouter has not been defined"

Encountering an error "indexRouter is not defined" while attempting to run the code below. Despite attempts to remove the line, additional errors persist. Can anyone clarify the rationale behind using the common variable router for both index.js and user.j ...

Traverse through an object in ReactJS

Having trouble iterating over an object in my ReactJS project and facing some content display issues. Check out this fiddle for reference - http://jsfiddle.net/8e039Ltw/ Here's the ReactJS code snippet:- class TodoApp extends React.Component { ...

When there is only one value, the BehaviorSubject can be hit multiple times

Recently, I implemented BehaviourSubject in a shared service to retrieve the current value when clicking a button. Everything seems to be working fine, however, there are instances where the API call within the subscribe block of BehaviourSubject is being ...

Angular's Routeprovider: Navigating Your Way through the

I am a newcomer to Angular and I encountered an issue while trying to implement routeProvider in my app. The error message that keeps appearing is: Uncaught Error: [$injector:modulerr] Failed to create module 'app' due to: Error: [$injector: ...

Add a JavaScript file into a PHP document

I've been searching for a solution in various forums, but the main answer I found doesn't seem to work for me. As someone new to Web development, I'm attempting to create a simple JavaScript program that takes a JSON string of products and ...

How can one access a specific element by its id that is located within an ng-template in Angular 6?

I have a question regarding accessing a button element inside an ng-template tag using its id in the TypeScript file. How can I accomplish that without encountering undefined errors? This is what I have tried so far: HTML <ng-template #popup > ...

This piece of code is causing my browser to lag

I am encountering an issue with fetching and adding values from a weather API to my HTML elements. My goal is to display the hourly forecast for today, starting from the current hour until midnight of the next day. In order to optimize space, I implemente ...