Breaking up an array of objects in JavaScript

I have an array of objects that I need to split based on the total amount. First, calculate the sum of the total amount, then split the array based on the total amount. If the total amount is greater than or equal to 4, they will be split and the key of the object will be used as a new key.

{
  25: [
    {
      id: 96207,
      name: "Client Name",
      phone: "123456789",
      amount: 1,
      …
    },
    {
      id: 96484,
      name: "Client Name",
      phone: "123456789",
      amount: 1,
      …
    },
    {
      id: 96208,
      name: "Client Name",
      phone: "123456789",
      amount: 2,
      …
    },
    {
      id: 96261,
      name: "Client Name",
      phone: "123456789",
      amount: 1,
      …
    },
    {
      id: 96367,
      name: "Client Name",
      phone: "123456789",
      amount: 1,
      …
    },
    {
      id: 96431,
      name: "Client Name",
      phone: "123456789",
      amount: 4,
      …
    },
    {
      id: 96432,
      name: "Client Name",
      phone: "123456789",
      amount: 1,
      …
    },
    {
      id: 96483,
      name: "Client Name",
      phone: "123456789",
      amount: 1,
      …
    },
    {
      id: 96515,
      name: "Client Name",
      phone: "123456789",
      amount: 2,
      …
    },
    {
      id: 96536,
      name: "Client Name",
      phone: "123456789",
      amount: 1,
      …
    },
    {
      id: 96560,
      name: "Client Name",
      phone: "123456789",
      amount: 1,
      …
    }
  ]
}

I want to divide it like this based on the amount if the total amount is greater than or equal to 4.

{
  25: [
    {
      id: 96207,
      name: "Client Name",
      phone: "123456789",
      amount: 1,
      …
    },
    {
      id: 96484,
      name: "Client Name",
      phone: "123456789",
      amount: 1,
      …
    },
    {
      id: 96208,
      name: "Client Name",
      phone: "123456789",
      amount: 2,
      …
    }
  ]
},{
  25: [ 
    {
      id: 96261,
      name: "Client Name",
      phone: "123456789",
      amount: 1,
      …
    },
    {
      id: 96367,
      name: "Client Name",
      phone: "123456789",
      amount: 1,
      …
    },
    {
      id: 96432,
      name: "Client Name",
      phone: "123456789",
      amount: 1,
      …
    },
    {
      id: 96483,
      name: "Client Name",
      phone: "123456789",
      amount: 1,
      …
    }
  ]
}, {
  25: [
    {
      id: 96431,
      name: "Client Name",
      phone: "123456789",
      amount: 4,
      …
    }
  ]
}, {
  25: [
    {
      id: 96515,
      name: "Client Name",
      phone: "123456789",
      amount: 2,
      …
    },
    {
      id: 96536,
      name: "Client Name",
      phone: "123456789",
      amount: 1,
      …
    },
    {
      id: 96560,
      name: "Client Name",
      phone: "123456789",
      amount: 1,
      …
    }
  ]
}

Can anyone help me achieve this result?

Answer №1

It appears that you have four items in your result instead of the expected five. While you may be considering merging the items after splitting to minimize the number of elements, I can offer you a solution that maintains the natural order without merging them. Feel free to reach out if you need any further assistance:

let input = {
  // Input object with multiple items
};

// Splitting logic based on amount value
let output = [];
for (let key in input) {
    let amount = 0;
    let obj = [];
    for (let item of input[key]) {
        if ((amount + item.amount > 4) && (obj.length)) {
            output.push({[key]: obj});
            obj = [];
            amount = 0;
        }
        amount += item.amount;
        obj.push(item);
    }
    if (obj.length) output.push({[key]: obj});
}

console.log(output)

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

Getting an Object in PostgreSQL without the need for square brackets wrapping when using Node.js and Express

I'm currently utilizing PostgreSQL alongside node-postgres: pool, Node.js, and express to execute some basic queries. The issue I encounter is that the returned object is wrapped within square brackets, but my preference is to receive it without them. ...

Add an asterisk before each line of comment when working in a TypeScript file using the VS Code IDE

Within my VS Code workspace, I am using the Typescript language and would like to format my comments across multiple lines with a specific style (look out for the star character) /** *@desc any text * any text */ However, when I attempt to write a comm ...

Change glb files to draco glb in the frontend

Can we encode and transform glb files into draco glb format using only frontend technologies (client side)? ...

How do I go about extracting and presenting the JSON data from the ESPN API?

In my current project, I am trying to utilize the jQuery library to work with API JSON data. Even though I am experienced in parsing JSON in PHP, I want to explore doing it with jQuery this time around. The goal is to extract information about each of the ...

Which javascript libraries or game engines can be utilized to create a 3D environment with x, y, z coordinates to monitor the movement of objects?

Currently, I am working on developing a basic web application prototype that will showcase the real-time tracking of up to five individual objects within a predefined room. While I have explored the possibility of using three.js for this project, I am wond ...

What is preventing me from obtaining the select and input values?

I'm currently facing an issue where I am unable to retrieve the values of customInput and customSelect and store them in the state. The challenge arises when trying to integrate these components into a react dashboard material-ui setup. Strangely, whe ...

Change from displaying web content to showing app content by utilizing Javascript

When using the mobile app, clicking on the user from the welcome screen redirects them to the next screen where a web-view is displayed through an API call. However, I am having trouble navigating back to the previous screen from this web view. It's ...

How is it possible that my code is continuing to run when it is supposed to be

My API has a limitation of 50 requests per minute for any endpoint. In the code snippet below, I filter objects called orders based on their URLs and store the ones that return data in successfulResponses within my app.component.ts. Promise.all( orders.ma ...

Validating Credit Card Numbers with Spaces

Currently, I am in the process of creating a credit card form that requires validation using checkValidity to match the specific card pattern that is dynamically added to the input field. For example, if a user enters a Mastercard number such as 545454545 ...

HTML and Javascript Form Integration for Sage Pay Purchase Button

Currently, I am working on a project that includes online payment options via PayPal and Google Wallet, with a "buy now" button. Now, my next step is to incorporate the Sage Pay "buy now" button onto the website using HTML and JavaScript. Although I have ...

Top method for shutting down a web browser tab without needing to wait for an AJAX reply

Is it necessary to wait for an ajax response before closing a window when trying to open, make an ajax call, and close the window as quickly as possible? This is how I am currently handling it: $.ajax({ url: requestURL, ty ...

What's preventing me from tapping on hyperlinks on my mobile device?

I'm currently working on a website (saulesinterjerai.lt) and everything seems to be functioning properly, except for the fact that on mobile devices, the links aren't clickable and instead navigates to other layers. How can I disable this behavio ...

Error: The `concurrent` command was not found when attempting to start the npm script

On my local machine, I've been attempting to set up Angular2. I successfully installed node and npm, but when I run 'npm start' I encounter the following error: root@sameer-Vostro-2520:/home/sameer/angular2/angular-2-beta-boilerplate# npm s ...

Access and retrieve pkpass files from a server using React

I've exhausted all options but still can't get it to work. I'm attempting to create an Apple wallet pass using https://github.com/walletpass/pass-js. When I download the pass on the node server where I've implemented it, everything work ...

Problem uploading files with ajax in Laravel version 6

I am encountering an issue while attempting to save a PDF file along with other input values using Ajax in Laravel 6 without utilizing the form HTML element. The error message "Call to a member function getClientOriginalExtension() on null" keeps popping u ...

Access the value of a JSON property, return null if the key is not found, all in one line of JavaScript code

How about a fun analogy in Python: fruits_dict = {"banana": 4, "apple": 3} num_apples = fruits_dict.get("apple", None) num_oranges = fruits_dict.get("orange", None) print(num_apples, num_oranges) The result would be: 3 None If we switch gears to Jav ...

Guide on retrieving a nested JSON array to extract a comprehensive list of values from every parameter within every object

A JSON file with various data points is available: { "success": true, "dataPoints": [{ "count_id": 4, "avg_temperature": 2817, "startTime": "00:00:00", "endTime": "00:19:59.999" }, ... I am trying to extract all the values of & ...

How to retrieve the current element in AngularJS version 1.x

I have done extensive research on how to get the current element in jQuery using $(this). However, I have not been able to find a similar method in AngularJS 1.x. Here is what I have tried: angular.element(this), but it does not work as expected. Below is ...

Troubleshooting Issue 415: Adding and modifying database records through jQuery AJAX in ASP.NET 6.0 MVC Application

Implementing the Add/Edit functionality for categories in my project led me to utilize a modal (pop-up) to transfer data to the backend without refreshing the page. To achieve this seamless interaction, I opted for ajax integration. However, encountering a ...

Error: Mocha Scope Function Undefined

Currently, I am following some TTD tutorials with Javascript and facing what appears to be a Javascript issue rather than a TTD problem. Here are the tests I have: 'use strict'; var chai = require('chai'); var expect = chai.expect; va ...