Using JavaScript to insert array elements at various positions

I am facing a scenario where I have an array structured as follows:

[
    { "Fare":10, "TotalFare":30 },
    { "Fare":20, "TotalFare":50 },
    { "Fare":30, "TotalFare":100 }
]

My objective is to accumulate all the fare values into a single variable at index 0.

For instance, accessing array[0].fare should yield the total amount of 60

I understand that this can be achieved with a for loop such as array[0].fare += array[i].fare

However, considering that my array contains data from 64/65 columns which need to be summed up, using the above method would make the code extremely lengthy,

Hence, I am wondering if there is a more efficient way to achieve this task?

Any suggestions or recommendations on how to approach this situation are highly appreciated.

Answer №1

If you want to calculate the total sum of values for each key in an array of objects, you can achieve this by using the combination of reduce method and Object.keys.

let data = [ { "Fare":10, "TotalFare":30 }, { "Fare":20, "TotalFare":50 }, { "Fare":30, "TotalFare":100 }];

data[0] = Object.keys(data[0]).reduce(function(obj, key){
  obj[key] = data.map(item => item[key]).reduce((acc, value) => acc + value);
  return obj;
},{});
console.log(data[0]);

Answer №2

array.reduce((accumulator, value) => accumulator + value);

I haven't had the chance to verify this, but I believe that utilizing array.reduce could help streamline your solution.

Answer №3

To begin, you must insert a new element at the start of the array by using the unshift() method. After that, iterate through the array using a forEach() loop like this:

var arr = [
    { "Fare":10, "TotalFare":30 },
    { "Fare":20, "TotalFare":50 },
    { "Fare":30, "TotalFare":100 }
];
arr.unshift({"Fare":0});
arr.forEach(obj=>arr[0].Fare += obj.Fare);
console.log(arr[0].Fare);

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

Trouble with executing jquery window.open during ajax success due to blocking

Encountering an issue when trying to open a new browser window in my ajax success call, as it is being blocked as a popup. After some investigation, I discovered that a user event must be associated with the window.open method to prevent this from happenin ...

When clicking on links that are not within the ng-view element, you will be redirected to the

I'm having trouble coming up with a name for this question, but here's my current situation This is the structure of my template: ├── index.html ├── ... ├── account │ ├── index.html │ ├── authorizat ...

Calculate the sum of the column values and disable the option to insert new rows in the UI grid

I am currently working on a ui-grid that has a column C which displays percentage values. There is a button labeled "add rows" that allows users to add new rows to the grid. However, the catch is that users can only add new rows until the total percentage ...

Error encountered while utilizing fullCalendar: Uncaught TypeError - Unable to convert undefined or null to object

I'm encountering an issue while attempting to implement a FullCalendar in my Laravel project, and the error message I receive is: Uncaught TypeError: Cannot convert undefined or null to object at entries (<anonymous>) at e (jquery.min.js ...

The thumbnail image is failing to load, and when I hover over an image, it moves upwards

I seem to be encountering an issue with a website I uploaded for testing. Everything appears to be working correctly when checked locally in Dreamweaver CS6. However, once the site is uploaded, some issues arise. When hovering over the images, a problem is ...

Choose all the checkboxes alongside the markers on Google Maps

On this page , I have included a checkbox labeled "Select All" at the bottom, which automatically checks all other checkboxes. Although the code below achieves what I want, the marker icons are not showing up. How can this be fixed? $(document).ready(func ...

Tips for creating visually appealing text on a web browser with the help of open-source libraries

Have you ever noticed that no matter how we display text on webpages, whether it's in a <p> tag or an <h1> tag, the result is always the same? (a screenshot of a rendering done in Firefox) Do you struggle with pixelated areas on the curv ...

Tips for locating a specific property deep within an array and pinpointing its exact location

Is it possible to use JavaScript to locate a property within an array that is nested within another array and return its "path"? Visualize a hierarchical group of nested arrays similar to this example: var bigBox = [ mediumBoxA = [ ...

How do I incorporate a standalone checkbox in a React Material-UI table without affecting row selection upon clicking?

I would like to have a distinction between clicking on a checkbox and clicking on a row. Specifically, I want the following behavior: when I click on the checkbox, only the checkbox should be checked; and when I click on the row, only the row should be se ...

What could be causing this jQuery selector to not select any elements?

Here's a simple question with some code that needs troubleshooting: $insides = $('<thead><tr><th><!--Blank space --></th></tr></thead><tbody><tr class="green-row"><td>Opportunities to D ...

Continuing a discussion in Bot Framework leads to an error: Unable to execute 'set' on a proxy that has been invalidated

I've been exploring the Microsoft Teams Bot Framework samples, specifically diving into bot-conversation. The source code for this can be found here. My goal is to send user messages to a backend server using a websocket and then post a response mess ...

How do I transform the date "Tue Nov 26 2019 16:00:00 GMT-0800" into the .NET JSON date format "/Date(1574812800000)/"?

I am looking to convert a date from ISO format to .NET JSON date format using JavaScript. For example, I want to change "Tue Nov 26 2019 16:00:00 GMT-0800" to "/Date(1574812800000)/". ...

Constructing a hierarchical tree structure using an array of objects that are initially flat

My goal is to create a hierarchical tree structure from a flat array: The original flat array looks like this: nodes = [ {id: 1, pid: 0, name: "kpittu"}, {id: 2, pid: 0, name: "news"}, {id: 3, pid: 0, name: "menu"}, {id: 4, pid: 3, name: ...

Issue with Express - Session not persisting across consecutive SSE requests

Currently, I am delving into Server-sent Events using Node.js and Express. I have successfully set up request handling and stream writing, but I am facing challenges with session management. The session does not persist between subsequent calls. Snippet o ...

Occasional TypeError when receiving JSONP response using jQuery .ajax()

Occasionally, I encounter an error message stating Uncaught TypeError: undefined is not a function when processing the JSONP response from my jQuery .ajax() call. The JSON is returned successfully, but sometimes this error occurs during the reading process ...

Using setInterval in React within an onChange event

I am facing a challenge where I need to set a setInterval inside an onChange event, which is typically done in componentDidMount. Currently, I have 2 dropdowns that filter data and then render a table. The dropdowns are controlled by their respective onCh ...

The callback for the array change listener is not receiving any arguments

Recently, I've been pondering a way to manage change listeners for arrays without relying on Observables or external libraries. My approach involves using a .json file containing an array of objects (specifically of type Rent) as my database. The goa ...

Empty box within a horizontal sequence

When dealing with a cube of values, it's simple to arrange it in a flat array and perform lookups using the index calculated by x*l^2 + y*l + z, where l is the length of each side. However, I am facing a challenge when the cube is hollow. One solution ...

Retrieve new data upon each screen entry

After running a query and rendering items via the UserList component, I use a button in the UserList to run a mutation for deleting an item. The components are linked, so passing the deleteContact function and using refetch() within it ensures that when a ...

Deliver real-time notifications to linked users by leveraging socket.io and node.js

Is there a solution for sending real-time updates to connected clients every second without using the setInterval() function in nodejs and socket.io? Please provide an alternative method that fits my specific scenario. ...