What is the most effective way to alter the elements in a JavaScript array based on the total count of another element's value?

I have a task where I need to manipulate an array by adding or removing elements based on the total count of another value.

let data = [
    {
  "details": [
    {
      "Name": "DataSet1",
      "Severity": "4",
      "Cost": 20
    },
    {
      "Name": "DataSet2",
      "Severity": "4",
      "Cost": 30
    },
    {
      "Name": "DataSet3",
      "Severity": "4",
      "Cost": 25
    }
  ],
  "charge": 45
}
];

My goal is to create a new array where the total value of the Cost property is close to, or less than, the charge property in the object. In the given example, the total cost is 75 which exceeds the charge of 45. So, my approach was as follows:

  1. Calculate the difference between the charge and the total cost. If the difference is greater than the charge, remove elements from the array to ensure that the new array's total cost is less or close to the charge. The modified array should look like this:
let newdata = [
    {
  "details": [
    {
      "Name": "DataSet1",
      "Severity": "4",
      "Cost": 20
    },
    {
      "Name": "DataSet3",
      "Severity": "4",
      "Cost": 25
    }
  ],
  "charge": 50
}
];

Is there a more efficient way to achieve this task? Are there any built-in functionalities in JavaScript that can help with this specific type of manipulation? Let me know if you have any suggestions or recommendations.

Answer №1

const numbers = {
  "value1": 10,
  "list": [{
      "Number": "Number1",
      "Category": "2",
      "Amount": 5
    },
    {
      "Number": "Number2",
      "Category": "2",
      "Amount": 8
    }, {
      "Number": "Number3",
      "Category": "2",
      "Amount": 7
    }
  ],
};
const addNumbersAndStayBelowValue =
  (value, array, begin = 0, currentTotal = 0, outcome = []) => {
    if (begin === array.length) return outcome
    const {
      Amount
    } = array[begin]
    const newTotal = currentTotal + Amount
    if (newTotal > value) return outcome
    return addNumbersAndStayBelowValue(value, array, begin + 1, newTotal, [...outcome, array[begin]]);
  }

console.log(addNumbersAndStayBelowValue(numbers.value1, numbers.list))

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

Guide to accessing and updating data in various tabs within a Google spreadsheet

I have two tabs named TAB A and TAB B. My goal is to iterate through TAB A and extract a set of values that I can then paste into TAB B. However, I encountered an error message saying, "Cannot read property 1, etc" function getValuesFromModal(form) { ...

Java: techniques for parsing this JSON

In my quest to extract information from a JSON object, I am seeking the values of either tel or user_id. Take for instance this JSON data: { "status":"ok", "account":{ "0":{ "user_id":"2", "thirdparty_id":"200", "tel":"28 ...

Within jQuery lies the power to perform multiplication operations effortlessly

I'd like to accomplish this using jQuery: var menuItems = document.getElementsByTagName("li"); for (var k = 0; k < menuItems.length; k++) { if (menuItems[k].className == "menu") { var child = menuItems[k].firstChild; if ...

How can you retrieve the X.509 Certificate from a P12 file using Node JS?

I obtained a p12 file that contains an X.509 Certificate. To handle this file, I am utilizing the forge library: var forge = require('node-forge'); var fs = require('fs'); var keyFile = fs.readFileSync("/path/to/p12/file.p12", 'b ...

Guide on how to use plain JavaScript to smoothly scroll to the page top

I'm attempting to replicate the functionality of scrollTop (using jQuery) using vanilla JS. When clicked, it should scroll to a specific element. While this works when the element is above the current scroll position, it does not function as intended ...

How to display JSON images in an Android listview

I'm facing difficulty in loading images from a JSON file to the listview on my Android app Although I know that I need to use BitmapFactory.decodeStream, I am unsure about how to proceed with the implementation Below are the details of my adapter an ...

Establishing a PHP session variable and then initiating a redirect to a new page through the HREF method

I am working on a table that pulls IDs from a MySQL table named auctiontable and displays them in rows. Currently, I can easily append ?aid="1"or ?aid="2" to the end of the href attribute to utilize $_GET. However, I want to prevent users from controllin ...

Can Mongoose handle document arrays editing and version control efficiently?

Currently working on a web application using Node.js and MongoDB/Mongoose, the main model in our project is Record which contains numerous subdocument arrays such as "Comment", "Bookings", and "Subscribers". However, when users click the delete button in ...

Is there a way to display my current connected clients to a new client using socket.io?

I am currently working on a project involving socket.io. Upon connecting to a new socket, my input username is displayed in the "usersDiv" where all clients are supposed to be listed. However, I've noticed that when I open another tab and input my nam ...

Unlock maximum screen viewing on your custom video player with these steps to activate fullscreen

I'm having an issue with my basic video player - when toggling fullscreen, it doesn't fill the whole screen even though I tried using .fullscreen{width:100%} without success after searching for a solution. html <div class='player-contai ...

Tips for accessing elements using document.getElementsByTagName

Greetings and best wishes for the holiday season! I hope everyone is cozy and safe. I need a little help with some code here, as I am fairly new to JavaScript but not entirely new to programming. Despite finding an answer on this site, I am still encounter ...

Tips for shuffling the sequence of EJS variables

I am currently working on creating a quiz that consists of multiple choice questions. In order to display the Question, Correct Answer, and 3 other wrong options, I am utilizing EJS variables. The format will be similar to the following example: Question: ...

contrasting two methods of declaring arrays in C++

There are two common ways to declare arrays and allocate memory for them in C++. 1. int a[3]; 2. int *b = new int[3]; I am curious about how C++ treats these two methods differently. a. With both declarations, I can access the array elements using a[1] ...

When running through a loop, the JSON array data containing the merged arrays is not being shown as expected

After combining the two PHP arrays $pricelist and $product and encoding them with JSON, the resulting JSON array is as follows: The PHP arrays look like this: Array ( [0] => Array ( [PriceList] => Array ( ...

Utilizing a StyledComponents theme within a Component

When creating a style called Link, the theme is contained inside of this.props. How can the theme be extracted from props and passed into the Link styled component? Error: ReferenceError - theme is not defined import React from 'react'; impo ...

Endless scrolling feature malfunctioning

On my profile_page.php, the default setting is to display 10 posts (10 rows from the database) for the user. If a user has more than 10 posts, and scrolls to the bottom of the page, the div should expand to reveal the remaining posts (maximum of 10). For e ...

Tips for eliminating unnecessary module js calls in Angular 9

https://i.sstatic.net/3R7sr.png Utilizing a lazy loading module has been efficient, but encountering challenges with certain modules like all-access-pass and page not found as shown in the image above. Is there a way to effectively remove unused module J ...

Execute the function that has been passed through a data attribute

I am attempting to execute a function using its name, which is passed through a data attribute in the HTML. I have made an attempt with the code below: HTML: <div class="generic-select" data-help-on-shown="genericFunction" > </div> ...

combine a pair of elements simultaneously

I recently developed a nested directive for a multitabbed form, and here is a simplified version: <outer> <inner heading="a" src="'a.html'" active="true"></inner> <inner heading="b" src="'b.html'"></inner ...

What is the reason behind using AJAX to attempt sending a new URL request on

Having a strange issue with my product list. When trying to edit a product by clicking on it, I am redirected to the product form where an AJAX request is supposed to be sent to getFiltersGroup. However, on error, the AJAX request is somehow being sent to ...