Search for objects in the array that have the same name, and then combine the values of those matching

I've done some research on various platforms, but haven't come across a solution to my specific issue. I'm looking to extract objects from an array and group them by their names in order to calculate the total hours for each matching object.

Consider this array:

var arr = [{name: 'Apple', hours: 6}, {name: 'Nokia', hours: 8}, 
           {name: 'Apple', hours: 4}, {name: 'Nokia', hours: 12},];
//expected output: [{name: 'Apple', totalHrs: '10'}], [{name: 'Nokia', totalHrs: 
         '24'}]

Any assistance would be greatly appreciated.

Answer №1

It's not feasible for an object literal to contain two identical keys. A workaround could involve adding up the values and using the name as a key instead.

let data = [{name: 'Banana',hours: 5}, {name: 'Samsung',hours: 10},{name: 'Banana',hours: 3}, {name: 'Samsung',hours: 15}];
let result = data.reduce((x, y) => {
    x[y.name] = (x[y.name] || 0) + y.hours;
    return x;
}, {});
console.log(result);

Answer №2

Try implementing a hashing function alongside a loop

var hash={}; // create an empty object to store names and hours
var arr = [{name: 'Samsung', hours: 4}, {name: 'LG', hours: 10},
           {name: 'Samsung', hours: 6}, {name: 'Sony', hours: 8},];
for(var i=0; i<arr.length; i++)
{
    if(arr[i].name in hash)
        hash[arr[i].name]+=arr[i].hours;
    else
        hash[arr[i].name]=arr[i].hours;
}
console.log(hash);`

Answer №3

If you want to filter an array by a specific property, you can use the following function:

function filterArrayByProperty(arr, property, value) {
        var resultsArr = [];
        for (var idx = 0; idx < arr.length; idx++) {
            if (arr[idx][property] == value)
                resultsArr.push(arr[idx]);
        }
        return resultsArr;
    }

To implement this function in your code, follow these steps:

var filteredItems = filterArrayByProperty(myArray, 'category', 'someCategory');
var totalSum = 0;
for(var idx = 0; idx < filteredItems.length; idx++)
    totalSum += filteredItems[idx].price;

console.log(totalSum);  

You could calculate the sum while looping through the array, but it's beneficial to have a reusable method like this one.

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

Contrast a multi-dimensional array against a regular array and populate any missing elements

My array consists of various waste categories and corresponding values for specific months: Array ( [Recycling] => Array ( [May 14] => 7040 [Jul 14] => 3920 [Aug 14] => 14560 [Sep 14] ...

Utilizing SlickGrid and DataView for calculating totals efficiently without the need for grouping

I am attempting to utilize Slick Grid and DataView to calculate column totals similar to the example shown here: . However, I do not want to group my rows. Therefore, I attempted not passing a getter and formatter into the dataView.setGrouping(..) method. ...

What could be the reason for my component not getting the asynchronous data?

Currently, I am delving into the intricacies of React and have been following a tutorial that covers creating components, passing props, setting state, and querying an API using useEffect(). Feeling confident in my understanding up to this point, I decided ...

Looking to attach the "addEventListener" method to multiple elements that share the same class?

I'm trying to use an event listener in JS to handle the logic in the "onClick" function, but it's only executing once. I've applied the same class to all four buttons, so I'm not sure why it's only working for the first one. HTML: ...

Jquery scripts seem to have a hit-or-miss success rate

Recently, I added a couple of Jquery scripts in my header to handle the fading in of a specific CSS class and scrolling down another one. Both of these classes are initially set to display: none in CSS, with Jquery responsible for making them visible. Here ...

What is the method for using a loop in Python to combine individual variables into an array?

I have numerous variables that store numeric values. These variables are named as ratios, for example ratio70 to ratio220. I would like to create an array from these variables in order to plot a graph with them. I attempted the following: ratioarr= (np ...

Creating a dynamic loader with JavaScript and PHP: A step-by-step guide

Currently focused on PHP development, my task involves retrieving data from a database using multiple queries. The database may contain anywhere from 10 records to 10,000 records. I am looking for a way to incorporate a progress bar that displays the com ...

Unable to redirect to the initial page successfully

My React application is using Redux-Toolkit (RTK) Query for user login functionality. When the user clicks the "logout" button, it should redirect to the home page ("/"). However, I'm facing an issue where clicking the "logout" button does not trigger ...

Retrieve the current URL of an IFRAME

How can I easily retrieve the current URL from an embedded iframe? The user will be navigating through various web pages. I assume that some JavaScript code would be needed for this task. ...

Using PLpgSQL, the program iterates through each record within a For Loop and then generates a

I am attempting to save a record or JSON data into an array and then return a JSON object from a function: CREATE OR REPLACE FUNCTION stat_per_day() RETURNS json AS $$ DECLARE RR RECORD; SS json[]; BEGIN FOR RR IN (SELECT DISTINCT date FROM time ...

Utilizing Bootstrap modal to insert data into phpMyAdmin database - a comprehensive guide

I'm attempting to insert data into my localhost database using a Bootstrap modal in conjunction with Laravel 5.2. Here is the PHP function I am using: public function addReport(Request $request) { $postreport = new PostReport(); $postreport- ...

React - updating key prop does not trigger re-render of child component

I have implemented react-infinite-scroll to display a continuous feed of data. My goal is to refresh the data feed whenever the user makes any changes to their settings. To achieve this, I am utilizing a key prop for the InfiniteScroll component. The conc ...

Switch up the text when the image link is being hovered over

Is there a way to change the text color of the "a" tag when it is not wrapping the img link? <li> <a href="# WHEN I HOVER THIS IMG LINK I WANT A TAG BELOW TO CHANGE COLOR"> <img alt="Franchise 16" src="#"></img> < ...

Make sure to always send back JSON data when using the default error handler in ExpressJS

I'm in the process of developing an API server using ExpressJS. I want to guarantee that the server consistently delivers JSON data rather than HTML data. While I can easily make the server respond with JSON for all customized routes, I encounter diff ...

Charting with multiple series

I am exploring a unique approach to creating a timeline chart. I am seeking advice on the best way to implement this in the world of JavaScript. My challenge is to create interactive milestones with descriptive text displayed on the Y axis, while displayi ...

Randomizing jQuery for duplicated HTML/jQuery elements

I'm facing a challenge with my jQuery and HTML scripts. I have a dropdown menu where a randomly generated number is displayed in the supplies field (voorraad) based on the selected option. However, when I clone this field using the add button, the fun ...

Having trouble with jQuery's 'OR' not functioning properly when iterating through mandatory input elements

In the process of creating a fallback for required HTML5 attributes for different input types, I encountered an issue with checking the ':checked' status of radio buttons and using the 'OR' || operator within the loop: if (self.val() = ...

How can I attach a jQuery plugin to a textbox with a changing class name?

I have a function that converts a regular text field into a datepicker: <input type="text" class="datepicker form-control" name="text-150" > var DatePicker = function () { if ($(".datepicker").length === 0) { return; } $(".datepic ...

Ways to implement a fixed navigation bar beneath the primary navbar using ReactJS

Utilizing ReactJS, I am endeavoring to create a secondary (smaller) navbar in the same style as Airtable's product page. My primary navbar is situated at the top and transitions from transparent to dark when scrolled. The secondary bar (highlighted in ...

The app.get() method in Node JS and Express requires three parameters, and I am seeking clarification on how these parameters work

Hey there, I'm new to this and have a question regarding my code using passport-google-oauth20. app.get('/auth/google/secrets', passport.authenticate('google',{failureRedirect: '/login'}), function(req,res){ res.redirec ...