When using Lodash, it will successfully operate on two objects but will yield a null value if presented

Check out this interesting plunker I have here...

I've noticed that when the 3rd item is deleted from the original, the calculation for total_expenses comes out as 23196. However, when the third object is included, total_expenses returns null. Is there something in my code that I might be overlooking?

The function total_expenses() utilizes _.reduce to sum up the values of a specific attribute across the collection.

$scope.loan.total_expenses = _.reduce(original, function(obj){
    var grand = 0;
    grand += obj.cost;
    return grand;
});

Answer №1

Your implementation of the reduce function seems to have an issue. To properly use reduce for summing values, make sure to provide an initial value as the third argument and return the incremented value in each step of the callback. Here's the correct code:

$scope.total = _.reduce(data, function(previousValue, currentValue) {
  previousValue += currentValue.amount;
  return previousValue;
}, 0);

In your scenario, with three objects in the array, the reduce callback will be executed three times:

  1. previousValue starts at 0, currentValue is data[0] => previousValue becomes data[0].amount.
  2. previousValue is now data[0].amount, currentValue is data[1] => previousValue updates to previousValue + data[1].amount, which is data[0].amount + data[1].amount.
  3. and so on.

Check out the demo: http://example.com/demo

Answer №2

When looking at the _.reduce function in the documentation, it specifies that the callback is bound to thisArg and invoked with four arguments: (accumulator, value, index|key, collection).

The first parameter of the _.reduce callback serves as the accumulator or sum value. This accumulated result is based on the return statement within the callback function. Initially, when the callback is triggered for the first time, it returns a number labeled as grand. Consequently, this number becomes the obj parameter during the subsequent iteration. However, this may not align with your intended outcome.

Since a number lacks a cost property, there arises an issue where you are essentially adding undefined to the initial number—leading to a resulting value of NaN (Not a Number).

Here is an example that should work (although @dfsq's version may be more preferable):

$scope.loan.total_expenses = _.reduce(_.pluck(original, 'cost'), function(sum, cost){
      return cost + sum;
    });

For further reference, check out the Updated Plunker.

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

I'm having trouble using Vueitify and the router - whenever I try to change components with Vue router, the URL updates but the component remains

Currently, I am working on setting up a single-page Vue application that utilizes Vuetify and the Vue Router. It seems like my routes are properly configured as: I can see them in the Vue tools, under both history and routes The URL and parameters update ...

Tips for resolving the strange behavior on a webpage with multiple active buttons labeled "portfolio"

I'm currently dealing with an issue regarding the behavior of a particular webpage that is quite unusual. I have provided a link to the Github page where this issue is occurring. Interestingly, the problem seems to be resolved when I remove the nav ta ...

What is the best way to display audio files for clients using a combination of Node.js and AngularJS?

After successfully converting my wav files to mp3 files using the ffmpeg converter, I am able to upload them to a designated "uploads" folder. However, I am facing difficulty in displaying these files on the browser. My current setup involves utilizing An ...

Issue with Wicket: unable to generate sound for resource paths

I am having some trouble with a path in my wicket project. There is a sounds folder located within the Web Pages directory. Within my JavaScript code, I am using the following path to play sounds: audioElement.setAttribute('src', 'sounds/s ...

Update your selection to ui-select and incorporate ngRepeat filters

Currently, I'm utilizing basic HTML select boxes to filter ngRepeat results in the following manner: <select ng-model="theFilter.choice"> <option value="">Any</option> <option value="Yes">Yes</option> <opt ...

"Insufficient rendering in three.js for all meshes to be displayed

Having an odd issue with 3d max 2013 obj to three.js 59 rev. In my 3d max scene, I originally have 5 cube objects. However, when I import them into the three.js scene, only 3 cubes are showing up. Also, their pivot point seems to be shared at the center of ...

Next.js React Hydration Issue - "Anticipated a corresponding <a> within the server HTML <a>"

Currently, I am encountering a hydration error while working on my Next.js project. The specific error message that keeps popping up is: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected serv ...

Suitability Criteria Matching Algorithm

In my project, I am developing an application to assess the compatibility of job applicants for a specific position. The process involves HR Executives outlining the required skills, qualifications, and degrees, which are then given a priority level rangi ...

Updating information within an ArcGIS Service using REST and JSON using jQuery/JavaScript

I've been attempting to update information in a feature within an arcgis service using REST and JSON. I've created a function that is supposed to be called, but the output I'm receiving is not providing me with any clear direction. I am als ...

What is the best way to manage feedback on various posts?

I am struggling to retrieve individual posts as it appears that I am only able to access the first one. Is there a way to uniquely identify each post using PHP and then retrieve the same value with JavaScript? Alternatively, I am open to any other solutio ...

Searching for hidden elements within a div using a filter option

An accordion is located inside a div and a search box has been added to the div with the intention of serving as a search filter. Some accordion elements are visible within the div while others are hidden. The problem arises when trying to make the filter ...

Adding static files to your HTML page with node.js

This is not a question about using express.static() In my application, I have multiple pages that share the same JS and CSS dependencies. Instead of adding <script> or <link> tags to every single page, I'm looking for a way to include the ...

Tips for updating the display by fetching data from a database through a websocket

I am looking for a solution to update a specific part of my webpage without having to refresh the entire content. On my index.html page, I have three panels displaying various ticket statuses. I want to automatically update the number of resolved tickets s ...

What is the process for importing specific modules from jQuery?

When working with webpack or browserify, what is the specific procedure required to import only the essential modules from jQuery as mentioned here? import {core, dimensions} from 'jquery' Unfortunately, this approach does not seem to be effect ...

Display or conceal elements depending on the values that have been toggled

My primary objective is to initially display all items and then hide or show them based on different properties that are toggled. I prefer not to chain filters because I only want to display items that have matching properties. I have 4 buttons that contro ...

How to enable the Copy to Clipboard feature for multiple buttons and transition from using an ID to a class identifier

Can someone please assist me? I have a copy to clipboard function that works well for IDs and a single button on my website. However, I need to modify it to work for multiple buttons and values with a class identifier. Unfortunately, I am unsure how to mak ...

Determine in JavaScript if one date occurs exactly one week after another date

Currently, I am tackling a date comparison task for our application. The main objective is to compare the Start Date inputted by the user with the Operator/Region Effective Date, which signifies when a new list of product prices becomes valid. Our aim is t ...

"Troubleshooting a malfunctioning PHP contact form that is not functioning properly

Here's some of my JavaScript code: var form = $('#main-contact-form'); form.submit(function(event){ event.preventDefault(); var form_status = $('<div class="form_status"></div>'); $.ajax({ url: $(th ...

Unable to resize div element using the change size function

When I click on a div, it should change size, and I want to write the onclick command in an external .js file instead of directly in the html page. Currently in html: <div id="box1" class="kaesten" onclick="changeSize('box1')"> Title 1 &l ...

What is the best way to invoke the update() and ScrollTop() methods in Angular for ngx-perfect-scrollbar?

Currently, I am utilizing the "ngx-perfect-scrollbar": "^5.3.5" library in my project. I have implemented a feature to toggle between "See More" and "See Less", however, when these actions are triggered, the Perfect Scrollbar does not update itself prope ...