combine all values into a single array with a list of arrays in JavaScript

After searching online, I couldn't find the answer I was looking for but I'm confident it's out there. Please direct me to it if this question has been addressed before. Apologies for any duplicate posts.

Hello, I am attempting to retrieve the values of a specific key within an array of arrays. My objective is to calculate the sum of a "column."

Here is an example:

Below is my array of arrays

var total = 0;

var dataset= [
    {"cost" : 5.00 , "name" : "Victor" },
    {"cost" : 6.00 , "name" : "Jack" },
    {"cost" : 7.00 , "name" : "Bill" },
    {"cost" : 8.00 , "name" : "Delilah" },
    {"cost" : 9.00 , "name" : "Robert" },
    {"cost" : 10.00 , "name" : "Marisa" }
]

Is there a way to get the total sum of all cost values in one iteration? Or can the cost values be displayed as a single array at once?

If I gather all the cost values, it should appear like this:

[5.00,6.00,7.00,8.00,9.00,10.00]

If there is a predefined function that I am unaware of, then I would expect something like this:

total = dataset["cost"].sum(); <-- pseudo code

console.log(total) //would print 45

I prefer not to iterate through each index of my dataset.

Thank you in advance

Answer №1

Why bother with iteration when JavaScript provides convenient built-in methods for us to use!

If you want to calculate the total sum of all the prices, simply follow these steps...

function calculateTotal( items ) {
    return items.reduce(function(total, current) { return total + current['price'] });
}

Just input your inventory data and get the final sum.

Answer №2

In order to calculate the total cost, you must iterate through the array using the array.reduce method.

const totalCost = data.reduce(function(accumulator, currentValue) {
  return accumulator + currentValue.price;
}, 0);

Answer №3

To calculate the sum of all values within an array, you can use the reduce method provided by Array.prototype:

var result = [3, 6, 9, 12].reduce(function(previousVal, currentVal, index, arr) {
  return previousVal + currentVal;
});
console.log(result)

Answer №4

Underscore simplifies the process:

const totalCost = _.reduce(_.map(dataList, 'price'), (total, price) => total + price);
return totalCost;

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 process for extracting filtered data from ReactDataGrid and saving it in an Excel file?

I'm currently working on exporting filtered data using ReactDataGrid and SheetJS. The excel file generated so far includes all the data from the table, but I am looking to export only the filtered data. Can anyone assist me with achieving this? Below ...

Exception Thrown When Element is Not Visible in Robot Framework

I encountered an ElementNotVisibleException error, even though the element appeared to be visible based on the screenshot in the logs. The button is controlled by JavaScript and can switch between enabled and disabled states. Here's the code for the d ...

JavaScript proxy feature: combining notifications after sorting an array

Seeking a solution to receive only one notification after sorting an array. Is there a method that accomplishes this? Thank you! const callback = function () { console.log (...arguments) } const array = [2,1] const handler = { set (target, prop, value ...

Using VueJS to dynamically manipulate URL parameters with v-model

Hello, I am new to coding. I am working on calling an API where I need to adjust parts of the querystring for different results. To explain briefly: <template> <div> <input type="text" v-model="param" /> ...

Issue detected with JavaScript object attribute containing hyphens prompts troubleshooting effort

I received a JSON response in the following structure. { "_meta" : { "next-person-id" : "1001", "totalPersons" : "1000" } } Utilizing Angular's $http service, I am attempting to retrieve this data and ac ...

Modifying an image's src using JavaScript is not possible

I'm attempting to modify the source of an image using a JavaScript function, but it doesn't seem to be working. The function is being executed within a mounted() method in Framework7. Here is my current setup: HTML: <div> <span> &l ...

Use Javascript or jQuery to traverse a tree in postorder and generate HTML markup

I am looking to generate HTML code similar to the following: <ul> <li>Submenu 1 <ul> <li>Submenu 1.1</li> <li>Submenu 1.2 <ul> <li>Subm ...

All Material UI components are aligned in a single row, spanning the entire width of the page

These are the components I am currently working with: Sandbox: https://codesandbox.io/s/6ipdf?file=/demo.js:78-129 <FormControl sx={{ m: 1 }} variant="standard"> <InputLabel htmlFor="demo-customized-textbox">Age& ...

Categorize elements in an array based on a specific keyword

Struggling with my AngularJS (1) application, I can't seem to figure out how to split an array of items into separate arrays grouped by item. In simpler terms, I have an array with different items and I want to group them by their uuid like this: [ ...

Element vanishing post JSON parsing

I have encountered an intriguing issue: I have developed an HTML/JS project that extracts information using XMLHttpRequest from the Scratch website. The main objective is to allow users to input their username and view their profile description on Scratc ...

What happens when AngularJS encounters real-time polymorphism during runtime?

An intriguing report by the Financial Times discusses how Shape Security, a Google-backed venture, is using shape-shifting code to outsmart hackers. Real-time polymorphism could revolutionize cyber security, attracting investors from major tech companies l ...

validating price ranges with the use of javascript or jquery

<!DOCTYPE html> <html lang="en"> <head> <title>My Page Title</title> </head> <body> <form method="post" action="process-form.php"> Price Range: From <input type="text" id="price-from"> ...

Utilizing jQuery for JSON parsing

Within my JavaScript code, I am working with the following array: var versions = [{"id":"454","name":"jack"}, {"id":"4","name":"rose"} {"id":"6","name":"ikma"} {"id":"5","name":"naki"} {"id":"667","name":"dasi"} ] I need to extract the name from this ar ...

Sluggish Performance of Material UI Table

Hey there! I've been working with Material-UI for a large data table, but I've noticed it's quite slow. Before reaching out on Github, I wanted to see if other users have any tips or workarounds to help improve performance. Here is the code ...

Having trouble getting the jQuery validate function to work properly with a select element

I have successfully implemented a validate function for my input fields : $.tools.validator.fn("#password", function(input, value) { return value!='Password' ? true : { en: "Please complete this mandatory field" }; }); $("# ...

Creating a list repeater using v-for in Vue.js 2 with computed property

Seeking assistance with adding computed columns to a table (last three columns). Suspecting the issue lies in the computed property not correctly referencing the record. Any simple solutions that I might be overlooking? Appreciate any thoughts or insights! ...

Asserting within a specific condition's scope in TypeScript

I am facing a similar situation, type Field1Type = { a: string; } type Field2Type = { b: string; c: number; } type ObjType = { field: Field1Type | Field2Type } const field = { b: "" c: 0 } const obj = { field } as ObjType i ...

Issues arise when utilizing pointers in function calls

I have created a structure array to store information about specific individuals and have implemented two functions to display this data. The third function (Wypisz) uses a pointer to call the specified display method. However, when I try to compile the co ...

When trying to extract information from a v-for loop and pass it into a method, I keep

After sending an array of data objects into a child component via props, I proceeded to use a v-for loop to display the elements exactly how I intended: <div class="col-md-3" v-for="product in products" :key="product.id" v ...

Is there a way to continuously run jQuery code or reset it?

Can you help me create a loop that will continuously run this script after it finishes executing, repeating the process indefinitely? I want to keep running this code over and over again. This script is using jQuery version 3.5.1 // Title var title1 ...