Angularjs: Adding Negative and Positive Numbers

How can I extract negative numbers and positive numbers separately from JSON data obtained from the server using the $http.get method? One of the fields in the data is called Credits, which contains both negative and positive values. Can anyone help me with this?

Array.prototype.sum = function (prop) {
    var total = 0
    for (var i = 0, _len = this.length; i < _len; i++) {
        total += parseInt(this[i][prop])
    }
    return total
}
$scope.totalCreadit = function (arr) {
    return arr.sum("credits");
}

This function provides the totals, but I need to separate the total for negative values and positive values.

Thank you in advance.

Answer №1

To separate positive and negative numbers in an array, you can leverage the filter and reduce methods,

var arr = [ 1, 2, 3, 4, 5, -2, 23, -1, -13, 10, -52 ],
    positive = arr.filter(function (a) { return a >= 0; }),
    negative = arr.filter(function (a) { return a < 0; }),
    sumnegative = negative.reduce(function (a, b) { return a + b; }),
    sumpositive = positive.reduce(function (a, b) { return a + b; });
console.log(sumnegative);
console.log(sumpositive);

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

Can an element in React be styled using the ID alone, without relying on className?

I'm in the process of transitioning an outdated website to React, and I'd prefer not to overhaul all the existing CSS files that have already been written. Many elements currently have their styles defined using an id. Is there a workaround to ma ...

The dygraphs library is experiencing an issue due to a discrepancy between the number of labels and the number of

Having trouble with the dygraphs. I've extracted an array from PHP that appears like this: data = [ { "DATA": "2016-01-22", "TOTAL": [ "7", "4", "20", "0" ] }, { "DATA": "2016-01-25", "TOTAL": [ ...

What could be the reason for XMLHttpRequest to freeze with no error until it reaches the default browser timeout limit

As a front end developer, I have some gaps in my understanding of how networks operate. When a Javascript XMLHttpRequest times out, the ontimeout handler gets triggered. In case the XMLHttpRequest.timeout property is not set (which is supported in modern b ...

What is the best way to turn off ajax functionality when detecting IE8?

Encountering a significant problem where every time the save/cancel button is clicked, IE8 freezes (while Firefox and Chrome work without issue). When JavaScript is disabled in the browser, it works correctly. There is a suspicion that an ajax call linke ...

audio enhancement in a web-based game

I'm having trouble getting a sound effect to play consistently in my game whenever there is a hit. Sometimes the sound plays, other times it does not! Here is the code I am using: <script> var hitSound = new Audio(); function playEffectSound ...

"Implementing a feature in AngularJS to dynamically display markers on a Google Map based on latitude and

I am a newcomer to AngularJS and I am attempting to pass my JSON latitude and longitude based on ID into the Google API. Here is the structure of my JSON file: { "totalCount":206, "deals":[{ "id":"2", "Name":"samir", "locations":[{ ...

refresh polymer components or make an ajax request within a custom element

I've been spending days on this issue with no success! My application relies on cookies for session handling and includes multiple custom elements imported in the header. Some of these elements need to access information from the 'cookie session& ...

Using async await syntax, retrieve a file in string format via HTTP with Node.js

Is there a way to download a file into memory through http in nodejs without relying on third-party libraries? This response addresses a related issue, but I am interested in avoiding writing the file to disk. ...

Deferred computed property fails to recognize the final character entered into the input field

I am facing an issue with my automated tests using selenium. The problem lies with a particular input field in a web form: <input data-bind="value: searchText, valueUpdate: 'afterkeydown'"></input> Here is the model associated with ...

Obtain the following image with every click

I have a div with images inside. I created two arrows (previous, next) within a larger div using the src of one of the images as the background URL for each arrow. My goal is to make the next arrow change the large image to the src of the following image w ...

Div expanding beyond intended size when media reaches maximum 468 pixels

When zoomimg is set to width: 145px; height: 145px; it ends up pushing the text that should be inside its parent element out of the parent. If you want to see the Zoomimg ProjectKort divs, check out the code below: .projectkort{ margin: 10px 0px 10px 0 ...

Authentication through Proxy and requests from nodes

I am attempting to make a get request to a website via https using the request module. However, I am behind a proxy that requires authentication. Despite my attempts to add the authentication, the connection to the site fails. I have experimented with add ...

"Exploring the world of asynchronous computations in jQuery Ajax: The next steps post-GET

When using ajax in jQuery with the request type, URL, and success functions, I often receive a JSON response. However, I face the challenge of needing to reformat the JSON arrays into a different structure, which can be computationally expensive. I am seek ...

Is there a way to combine all referenced pages into the main page using JQuery?

Is there a way to dynamically replace external CSS and JS file references in an HTML file with the actual contents of those files using Jquery or straight JavaScript? For example, instead of: <link rel='stylesheet' id='style-css' ...

Is it possible to create a data table with ascending or descending numbers while also including text

I am trying to sort a column in ascending/descending order with numbers ending in x. MyCode : { targets: [4], visible: true, searchable: true, render: function(data, type, row) { re ...

Improving model in AngularJS

Check out this Plunker: http://plnkr.co/edit/s9MwSbiZkbwBcPlHWMAq?p=preview I noticed that when I input the same information twice, the latest data overrides the previous one. How can I ensure that the model doesn't update in such cases? $scope.per ...

Having problems with the cache function not functioning properly with jQuery's `.load()`?

I have implemented a standard PHP cache script on my page.php file. $cache = 'the_location/'.$id.'.html'; $expire = time() -3600 ; if(file_exists($cache) && filemtime($cache) > $expire) { readfile($cache); ...

What method yields the highest productivity when filling a table?

What is the most efficient way to update data in an HTML table quickly? I am utilizing MVC3 and have a table that needs to be updated on multiple clients every few seconds. I'm currently using ajax calls to return a partial view containing the table. ...

The issue with the table inside a bootstrap modal is that it is not properly sized and does

I am facing an issue with a modal that has two columns. One of the columns contains a table which is too wide and requires horizontal scrolling. I need help to make the table fit into the column without any scrolling problems. The table should be able to s ...

Service for Posting in Angular

I am looking to enhance my HTTP POST request by using a service that can access data from my PHP API. One challenge I am facing is figuring out how to incorporate user input data into the services' functionality. Take a look at the following code snip ...