Manipulating Arrays with Conditions in JavaScript

Here is an array I need to work with:


0: {productid: "001", containersize: "20", ContCount: 10}
1: {productid: "002", containersize: "20", ContCount: 9}
2: {productid: "001", containersize: "40", ContCount: 4}
3: {productid: "001", containersize: "20", ContCount: 20}
4: {productid: "003", containersize: "20", ContCount: 18}
5: {productid: "001", containersize: "40", ContCount: 7}
6: {productid: "003", containersize: "40", ContCount: 25}

I aim to transform this data into a new array like so:


0: {productid: "001", containersize20: 30, containersize40: 11, total: 41}
1: {productid: "002", containersize20: 9, containersize40: 0, total: 9}
2: {productid: "003", containersize20: 18, containersize40: 25, total: 43}

The purpose is to sum up the counts of containers based on product type and container size.

Initially, I used the following code snippet:


var group_to_values = data.reduce(function (obj, item) {
            obj[item.productid] = obj[item.productid] || [];
            obj[item.productid].push(item.ContCount);
            return obj;
        }, {});

        var groups = Object.keys(group_to_values).map(function (key) {
            return {productid: key, ContCount: group_to_values[key]};
        });

At this stage, I am facing difficulty in proceeding further with the transformation process.

Answer №1

Utilizing the reduce method is an ideal solution for this scenario. By iterating through the structure and creating a result object with keys based on specific criteria, you can then extract the values array:

const data = [
  {productid: "001", containersize: "20", ContCount: 10},
  {productid: "002", containersize: "20", ContCount: 9},
  {productid: "001", containersize: "40", ContCount: 4},
  {productid: "001", containersize: "20", ContCount: 20},
  {productid: "003", containersize: "20", ContCount: 18},
  {productid: "001", containersize: "40", ContCount: 7},
  {productid: "003", containersize: "40", ContCount: 25}
];

const res = Object.values(data.reduce((a, e) => {
  if (!(e.productid in a)) {
    a[e.productid] = {
      productid: e.productid, 
      containersize20: 0,
      containersize40: 0,
      total: 0
    };
  }
  
  a[e.productid].containersize20 += e.containersize === "20" ? e.ContCount : 0;
  a[e.productid].containersize40 += e.containersize === "40" ? e.ContCount : 0;
  a[e.productid].total += e.ContCount;
  return a;
}, {}));

console.log(res);

Answer №2

You're making progress in the right direction, consider condensing your code using a single `.reduce` function to create an object indexed by `productid`. Then, you can extract the values from this object and transform them back into an array. Remember to convert the `containersize` string to a number for proper addition:

const input = [
  {productid: "001", containersize: "20", ContCount: 10},
  {productid: "002", containersize: "20", ContCount: 9},
  {productid: "001", containersize: "40", ContCount: 4},
  {productid: "001", containersize: "20", ContCount: 20},
  {productid: "003", containersize: "20", ContCount: 18},
  {productid: "001", containersize: "40", ContCount: 7},
  {productid: "003", containersize: "40", ContCount: 25}
];
const output = Object.values(input.reduce((a, { productid, containersize, ContCount }) => {
  if (!a[productid]) a[productid] = {
    productid,
    total: 0,
    containersize20: 0,
    containersize40: 0,
  };
  a[productid]['containersize' + containersize] += ContCount;
  a[productid].total += ContCount;
  return a;
}, {}));
console.log(output);

It's important to note that this implementation is pure JavaScript, not jQuery. Often, built-in JavaScript functionalities can be just as effective as jQuery.

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 method in Java to extract the name of the oldest individual by utilizing split strings and arrays?

I can't seem to solve this problem no matter how long I stare at it. The task is to find the oldest person's name by splitting strings and determining the name with the highest age. You can find this exercise at . > Sample Input: Johnny, 5 &g ...

Solving the problem of 'json mime-type on 2003 server

I am currently facing an issue: On a 2003 server with iis 6, I have a functioning solution. However, during every deployment of the solution, I find myself having to manually configure the MIME type on the iis. Although I have implemented this in my web ...

The positioning of the JQueryUI menu is experiencing some issues

My goal is to dynamically create menus using JQueryUI menu widgets. Check out this Plunker Example for Dynamic Menu Creation with some issues I am facing an issue where the menu is not positioning itself correctly. It always appears near the bottom of my ...

Have you ever wondered how to disable a tooltip in React Material UI after clicking on it? Let

I am working with a Material-UI tab component and I would like to include a tooltip feature. The issue I am facing is that the tooltip does not disappear when I click on the tab. It should hide after clicking on the tab. Currently, the tooltip remains vi ...

Express.js not redirecting to Angular route, app not starting

I have the following setup in my node.js app.js: app.use('/', routes); app.get('some_api', routes.someApi); app.use(function (req, res) { res.sendFile(path.join(__dirname, 'public', 'index.html')); }); Additio ...

Creating a button that redirects to an external link in CodeIgniter:

Hello everyone, I'm new here and I could really use some assistance with a problem. I am trying to link the button labeled 'lihat rincian' and each row of tables to redirect to an external link like Here's a snapshot of my datatables ...

Assigning a value to an integer from a compatible integer data type

I've encountered a compile error in the highlighted portion. Can someone assist me in pinpointing the mistake? Below is my code snippet... void _multiDimensionalArray(){ int row = 10; int column = 10; cout << "\n\n For a ...

Building an Array in C++ Containing Class and Derived Objects

My goal is to establish two arrays: regDiceBag, which will consist of 10 base class objects Die, and another array containing 5 base class objects and 5 derived class objects LoadedDie. While I am able to initialize the first array using Die[] regDieBag[10 ...

(C) Procedure involving a two-dimensional array

Currently, I'm faced with a task to create the following function: int **multiplyM(int MA[][], int MB[][], int n, int m) This function is supposed to multiply two matrices - MA with dimensions n by n, and MB with dimensions n by m. Although everythi ...

Challenges with ioException within the Sudoku algorithm

//Error found: NullPointerException in thread "AWT-EventQueue-0" at Sudoku.azar(Sudoku.java:94) at Sudoku$EscuchadorStart.actionPerformed(Sudoku.java:106) Upon clicking the Start button, an error occurred indicating that the program compiles but does not ...

Create a custom definition for the useSelector function within a separate TypeScript file in a React

Question: Is it possible to define a type like <TRootState, string> in an external file and use it directly inside multiple Component files? External file: export type TUser = <TRootState, string> // This method does not work Component's ...

Why does the click on the download link result in the image opening instead?

I'm having an issue with my code that is supposed to download a file, but instead it opens the file. What am I doing wrong? <html> <body> <p>Click on the Image to download the image:<p> <a href="/website/image1.jpg" downl ...

Is there a way for me to retrieve the data returned from a worker thread?

In my quest to understand how worker-threads function, I've come across this useful example: https://github.com/heroku-examples/node-workers-example.git REMINDER: Ensure Redis is installed and running for this example My primary challenge lies in r ...

In my approach to locating the subarray with the largest sum modulo x, I employ an iterative search method utilizing Binary Search

Currently tackling a challenge on hackerrank.com that involves finding the subarray B from a given array A and modulo m, where sum(B)%m yields the largest value. Essentially, we are looking for the subarray with the highest sum mod m. My strategy so far i ...

Checking the Json response with Java

Can someone help me extract the textType and taxAmount values from the JSON response below? { "taxExempt": false, "billingAddress": { "addressLine1": "Millers Rd", "addressLine2": "", "city": "Bengaluru", "postalCode": "560052", "sta ...

Trouble with the installation of pg-native dependency

I'm currently facing difficulties with adding the pg-native dependency to my project directory. When attempting to execute my index.js file, an error stating it cannot "resolve the dependency pg-native" appears even though I don't recall invoking ...

Obtain a specific element in Puppeteer JS by utilizing the waitForSelector function to detect when its class name changes

I am faced with a situation where I need to wait for a specific element to change its classes dynamically. The challenge arises when utilizing the waitForSelector function, as it fails to work when no new element is added to the DOM. Instead, it is the &l ...

Developing a new webpage component in Selenium using C# and retrieving the corresponding feedback

I am currently working on adding a new element and I need to retrieve a URL as the response. However, I am unsure of how to capture the response from this new element. Any advice or suggestions would be highly appreciated. public void Initialize() { ...

The Bootstrap modal window refuses to shut down

In my React application, I am utilizing Bootstrap modal functionality. One specific requirement is that the modal window should remain open when clicking on the modal backdrop. To achieve this, I have implemented the following code: $(".modal").modal({"ba ...

Why isn't my watch function functioning properly within Vue?

In my JS file, I have two components. The file starts with this line: const EventBus = new Vue(); I am trying to pass two strings, 'username' and 'password', from the first component to the second component, but it's not working. ...