In JavaScript, calculate the total sum of values in an array of arrays by focusing on two specific keys

Within my array, I have dates, products, and product quantities. On occasions, the same products appear on the same day, and I want to combine them only if the date matches. Here is my array:

[
    {date:"day2",sku:"product1",qty:1},
    {date:"day1",sku:"product1",qty:1},
    {date:"day1",sku:"product2",qty:1},
    {date:"day2",sku:"product2",qty:1},
    {date:"day1",sku:"product1",qty:1},
    {date:"day2",sku:"product2",qty:1},
    {date:"day2",sku:"product2",qty:1},
    {date:"day3",sku:"product1",qty:3}
]

This is what I expect as output:

[
    {date:"day1",sku:"product1",qty:2},
    {date:"day1",sku:"product2",qty:1},
    {date:"day2",sku:"product1",qty:1},
    {date:"day2",sku:"product2",qty:3},
    {date:"day3",sku:"product1",qty:3}
]

Answer №1

To achieve this, you can utilize the reduce method followed by using Object.values():

var items = [ {date:"day2",sku:"product1",qty:1}, {date:"day1",sku:"product1",qty:1}, {date:"day1",sku:"product2",qty:1}, {date:"day2",sku:"product2",qty:1}, {date:"day1",sku:"product1",qty:1}, {date:"day2",sku:"product2",qty:1}, {date:"day2",sku:"product2",qty:1}, {date:"day3",sku:"product1",qty:3}];

var finalResult = Object.values(items.reduce((acc, {qty,...rest})=>{
   const combinedKey = Object.values(rest).join('|');
   acc[combinedKey] = acc[combinedKey] || {...rest, qty:0};
   acc[combinedKey].qty+=qty;
   return acc;
},{}));

console.log(finalResult);

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

Summernote information embedded with HTML elements

I just started using the summernote text editor and I'm trying to figure out how to extract the content from the textarea without all the HTML tags. This is what I have in my code: <textarea class="summernote" id="summernote" ng-model="blog.c ...

"Is it possible to draw on top of a canvas element that's already been

I'm currently working with an OpenLayers map that includes WMS layers with time steps. My goal is to create a loop that updates the time for each step and then saves the image once it's rendered. I've been referencing the example code from t ...

Tips for changing a "raw" DOM Event into a React SyntheticEvent

Currently, I am working with two separate libraries. The first library emits "raw" DOM events (lib.dom.d.ts), while the other library consumes React.SyntheticEvents. I am seeking advice on the most efficient method to transform the raw event into a Synthe ...

Flask app facing compatibility issues with jQuery .getJSON

I am encountering an issue with my flask application where I am attempting to send JSON data to the browser and render it. However, the line containing $.getJSON() is not executing as expected. Here is a breakdown of the relevant code: app.py from flask ...

Javascript handling scrolling and repositioning

When using the scrollBy() method in the window object of JavaScript, there are two arguments required. But what do these arguments actually represent? The resource I am currently studying from states that it is "the number of pixels to scroll by," but I am ...

React JS makes it simple to create user-friendly cards that are optimized

I have a collection of objects that include a name and description. The name is short and consists of only a few characters, while the description can vary in length. I am looking to showcase this data within Cards in my React project, and have tried using ...

When opening a dialog at the bottom of the page, the window will automatically scroll to the top

I'm encountering an issue with a page that has a width exceeding 100% (2000px). Whenever I click to display a dialog from a button located at the end of the horizontal page, the window automatically scrolls back to the beginning of the page before sho ...

Guidelines for populating data with an array

I have the following array: const dataArr = [[15, 14, 5], [16, 10, 2], [17, 6, 13], [18, 4, 8], [19, 7, 4]]; Now, I am populating another array using the above data as shown below: for (let i=0; i<dataArr.length; i++){ newData.push(dataArr[i]); ...

Learn how to show image information in a separate div by clicking on the image using jQuery

Is there a way to show or hide information of an image in a separate div by clicking on the image itself? $(document).ready(function () { $(".cell").click(function () { $(this).find("span").toggle("slow"); }) }); <div class="cell"> ...

Struggling to Enforce Restricted Imports in TypeScript Project Even After Setting baseUrl and resolve Configuration

I am facing challenges enforcing restricted imports in my TypeScript project using ESLint. The configuration seems to be causing issues for me. I have configured the baseUrl in my tsconfig.json file as "src" and attempted to use modules in my ESLint setup ...

Retrieve information using the useEffect hook on a server-side rendered webpage

I am currently working on a project using React JS and Next JS. The page is dynamic, utilizing getStaticPaths and getStaticProps to fetch most data on the server side for rendering. However, there are certain pieces of data that require a token stored in l ...

Transferring information to PHP script using only JavaScript (Ajax)

I have a good understanding of jQuery: $.ajax({ method: 'POST', url: 'send-data-to.php', data: {data:"data"} }) However, I am unsure of how to send data that is accessible via $_POST using pure JavaScript. The reason for my inqu ...

Extract list of string or integer values separated by commas from a JSON and convert them into an array

My current task involves extracting key/value pairs stored in JSON format. Sometimes, the values of these pairs can be arrays. Below is an example of such a JSON file: { "name":"abc", "address":"some address value", "phonenumber": "\"123123&bso ...

What is the best way to showcase nested array information from a JSON file on an HTML webpage?

students.json { "students": [ { "studentname": "Rohit Kumar", "grade": "A", "student": [ { "SNo": "1", "Subject": "Maths", "Concept": "Numbers" }, { "SNo": "2", ...

What is the best way to enable object references in Node modules?

I've been working on my Express.js web app and I've realized that as I extract parts of my code from the main app.js file into separate modules, I sometimes need to access objects from the main file. I'm trying to figure out the best way to ...

Incorporate JavaScript to dynamically fetch image filenames from a directory and store them in an array

By clicking a button, retrieve the names of images from a folder and store them in an array using jQuery. I currently have a script that adds images to the body. In the directory images2, there are 20 images stored. The folder images2 is located in my i ...

Sorting and searching through multiple values using data structures in Rails

Currently, I am developing a software tool that takes input data from your golf game to determine your handicap. In addition to this feature, I have also included a table on the side of the program similar to Excel. This table consists of golf course names ...

JQuery - Triggering $(document).ready() before the elements are fully loaded

While working on retrieving data from a MVC3 action that returns Json with parameters and content as a string, I encountered an issue. After appending the content to a div, a JQuery event placed in a partial view's document.ready function executes bef ...

Open a new HTML page with jQuery with a click event trigger on an iframe element

Hello everyone, I have a simple question as I am still learning about Jquery. I am attempting to load another .html page whenever a figure element is clicked on this .html page. However, the script tag is not working as expected. Can someone please assist ...

The AJAX request was a success, but unfortunately there is no usable data available

After submitting the registration form, jQuery sends the data to register.php, which then responds with JSON data for jQuery to process. Everything seems to be functioning correctly as users are successfully registered. The network response tab shows that ...