Find the total of values in an array that may be null or undefined

In this scenario, I have an array that looks like this:

myData = [[2, null, null, 12, 2],
          [0, 0, 10, 1, null],
           undefined];

The goal is to calculate the sum of each sub-array, resulting in an array like this: result = [16, 11, 0]. The idea is to replace both null and undefined with zeros.

My current method works well excluding the case where the last element is undefined:

MyCtrl.sum = MyCtrl.myData.reduce(function (r, a) {
    a.forEach(function (b, i) {
        r[i] = (r[i] || 0) + b;
    }); 
    return r;
}, []);

I attempted different approaches to handle the substitution of zero for null or undefined within a sub-array but encountered difficulty:

MyCtrl.sum = MyCtrl.myData.reduce(function (r, a) {
    if(a) {
    a.forEach(function (b, i) {
        r[i] = (r[i] || 0) + b;
    }); } else {
        r[i] = 0;
    }
    return r;
}, []);

An issue arises stating that 'i' is not defined in the else statement.

If you have any suggestions or solutions to this problem, please share your insights.

Answer №1

To compare the values, you can assess the inner array and if it is unspecified, then set an array as the default value.

When adding them up, you may opt to use zero as the default value in a reduce function with zero as the starting point.

var array = [[2, null, null, 12, 2], [0, 0, 10, 1, null], undefined],
    result = array.map(a => (a || []).reduce((s, v) => s + (v || 0), 0));
    
console.log(result);

Answer №2

If you want to consolidate the data in JavaScript, lodash can be helpful:

let exampleData = [[2, null, null, 12, 2],
          [0, 0, 10, 1, null],
           undefined];
// Combine array elements
let mergedData = _.filter([].concat.apply([], exampleData), (value) => {
    return _.isNumber(value);
});

let totalSum = mergedData.reduce((x,y) => {
        return x+y;
});
console.log(mergedData);
console.log(totalSum);

Answer №3

Have you considered utilizing the .map method?

var myData = [
    [2,null,null,12,2],
    [0,0,10,1,null],
    undefined
];

var sum = myData.map(function(item,index){
    if(!item) return 0;
    if(item.length < 2) return item[0];
    return item.reduce(function(i1,i2){return i1+i2});
});;

console.log(sum);//[ 16, 11, 0 ]

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

Troubleshooting: Issues with window.location.href and window.open within an iframe

Code Update <div> <button type="button" class="submit btn btn-default" id="btnSubmit">Submit </button> <button type="button">Cancel</button> </div> <script> $("#btnSubmit").click(function(e) { ...

The hyperlink in the mobile version of the mega menu is unresponsive in HTML

I am encountering an issue with the navigation menu on my Laravel website. The menu links work correctly on the desktop version, but none of the anchor tag links are functioning properly on the mobile version. HTML <div class="menu-container"> < ...

What is the proper syntax for using .focus() with the nextElementSibling method in typing?

As I strive to programmatically shift focus in my form using nextElementSibling, I encounter a challenge with typing variables/constants due to working with Typescript... I have managed to achieve success without typing by implementing the following: myF ...

Determine if a user's inputted number matches a randomly generated number using Javascript

I am trying to generate a random number, prompt the user to input a number, compare the two, and display a popup indicating whether they match or not. Below is the code that I have written for this functionality. function generateRandomNumber() { ...

Transferring an object from the factory to the controller

I'm currently working on setting up a factory that sends an ajax request to an API and then returns a data object. Here is the code snippet I have written: app.factory('Test', function($http, $q) { var data = {response:{}}; var getM ...

The controller is being utilized by two different directives

Consider the following scenario: function directive() { return { template: '{{foo.name}}', controller: ctrl, controllerAs: 'foo' } } function ctrl($attrs) { this.name = $attrs.name; } If you have t ...

Angular is giving me an undefined Array, even though I clearly defined it beforehand

I've been working on integrating the Google Books API into my project. Initially, I set up the interfaces successfully and then created a method that would return an Array with a list of Books. public getBooks(): Observable<Book[]>{ ...

Looking for assistance in resolving performance problems with numerous elements in AngularJS

I am currently experiencing performance issues with AngularJS, particularly when a large number of "elements" are added to the page. It is taking around 20 seconds for my computer to render the elements in this folder structure. Each folder contains 10 sub ...

Verifying a checkbox selection within an Autocomplete feature using MUI

[ { label: 'First', checked: false }, { label: 'Second', checked: true } ] Here is a brief example of how the data may be structured. I am utilizing Material UI's Autocomplete feature to enable searching based on labels. Thes ...

What is causing the issue with $(document).append() method in jQuery version 1.9.1?

Why is the following code not functioning properly in jQuery 1.9.1? It worked fine in previous versions. $(function () { $(document).append(test); document.write('done'); }); var test = { version: "1.0", }; JSFiddle: http://jsfiddl ...

Unusual behavior in PHP when an integer is explicitly cast to a boolean in an if

Seeking assistance from anyone who can lend a hand. I have a function called ret_error() that is triggered when there's an error accessing a table in a database, such as "could not connect" or "record not found". This function returns an array with t ...

The PHP random number generator appears to be malfunctioning when being compared to the $_POST[] variable

In this section, random numbers are generated and converted to strings. These string values are then used in the HTML. $num1 = mt_rand(1, 9); $num2 = mt_rand(1, 9); $sum = $num1 + $num2; $str1 = (string) $num1; $str2 = (string) $num2; The following code ...

How can I verify if an unsupported parameter has been passed in a GET request using Express/Node.js?

Within my node.js backend, there is a method that I have: app.get('/reports', function(req, res){ var amount = req.param('amount'); var longitude = req.param('long'); var latitude = req.param('lat'); var di ...

Design a unique input component tailored specifically for react-day-picker

While working on a custom Material UI component for DayPickerInput, I encountered an issue where the onDayChange event triggers an error. handleToDateChange = (selectedDay, modifiers, dayPickerInput) => { const val = dayPickerInput.getInput().value ...

What is the best way to import the three.js OBJLoader library into a Nuxt.js project without encountering the error message "Cannot use import statement outside a module

Beginner here, seeking assistance. Operating System: Windows 10. Browser: Chrome. Framework: Nuxt with default configurations I have successfully installed three.js using npm (via gitbash) by running npm install three --save. It is included in the packag ...

Having trouble configuring the proxy port for my Vue.js application

I'm currently developing a web application using vue.js for the front end and node.js for the server. Vue is running on port 8080 and Node.js is running on port 3001. To make API calls, I have set up a proxy in my vue.config.js file, but it doesn&apos ...

Exceeded maximum file size event in Dropzone

I am currently implementing dropzone in my form to allow users to upload images. In the event that a user selects a file that exceeds the configured limit, I want to display an alert message and remove the file. Below is my current configuration: Dropzone ...

Cannot see the created item in Rails application when using RSpec, Capybara, Selenium, and JavaScript

Currently, I am in the process of developing a web store. The key functionality is already implemented where all products are displayed on one screen along with the list of ordered items. Whenever a product is selected for ordering, it should instantly app ...

Setting the state of a nested array within an array of objects in React

this is the current state of my app this.state = { notifications: [{ from: { id: someid, name: somename }, message: [somemessage] }, {..}, {..}, ] } If a n ...

`Finding specific components or pages within an AngularJS application`

I came across a unique webpage for an Angularjs based project. I am looking to develop an autofiller and autoclicker feature. To achieve this, I need to identify pages or subpages uniquely (especially in cases of Ajax-based changes). The major challenge ...