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

obtain data in JSON format from a Node.js server and display it on an HTML

I am currently working on a feature that involves sending an AJAX request to the server and receiving the output of a MySQL query on the page http://localhost:3000/result.html upon clicking a button. <body> <form action="/setLocation" method=" ...

Exploring the power of Angular's ng-repeat to generate hierarchical lists

I am looking to display a structured list of layers and sublayers by looping through an object using ng-repeat. var lyrslist = [ { layername: "Base Maps", layertype: "layer" }, { layername: "Open Street Map", layertype: "sublayer" },    { layer ...

Issue: Unable to locate the module 'babel-code-frame' in VUEJS (ESLINT)

Here are the current versions: -npm: 6.14.4 -node: v10.19.0 -eslint: v5.0.1 -linux: ubuntu 20.04 This is my script: vue create vue1 cd vue1 npm run serve This is my package.json: { "name": "vue1", "version": "0. ...

Transferring information between pop-up and webpage

I have developed a simple form within an ERP system that allows users to create quick support tickets. However, instead of manually inputting the client ID in the form, I want to provide them with a more user-friendly option. My idea is to include a search ...

Error message: The Liferay JavaScript Function has not been defined

I am a newcomer to Liferay and have been attempting to utilize Ajax within my scripts, but unfortunately, the code does not seem to load correctly in the browser. I even tried testing it by simply adding an alert. Every time I try, I encounter the "functi ...

How can I use Angular to toggle a submenu based on a data-target attribute when clicked?

Struggling to implement a functionality using ng-click to retrieve the data-target attribute of a clicked angular material md-button, in order to display the submenu when a topic is clicked on the sidenav. The navigation structure consists of md-list with ...

Generating step definitions files automatically in cucumber javascript - How is it done?

Is there a way to automatically create step definition files from feature files? I came across a solution for .Net - the plugin called specflow for Visual Studio (check out the "Generating Step Definitions" section here). Is there something similar avail ...

Challenges with fetching data from APIs in NextJs

I am currently working on a basic NextJs TypeScript application with the app router. The following code is functioning correctly: export default async function Page() { const res = await fetch("https://api.github.com/repos/vercel/next.js"); ...

How to customize the arrow color of an expanded parent ExpansionPanel in material-ui

Currently facing a challenge in customizing material-ui themes to achieve the desired functionality. The goal is to have the expansion panels display a different arrow color when expanded for improved visibility. However, this customization should be appl ...

Obtain the specific key's value from a new Map state

In my code, I've defined a variable called checkedItems as a new Map(); When I try to console.log(checkedItem), the output is as follows: Map(3) {"1" => true, "1.5" => true, "2" => false} Is there a way for me to ...

Issue encountered while utilizing property dependent on ViewChildren

Recently, I designed a custom component which houses a form under <address></address>. Meanwhile, there is a parent component that contains an array of these components: @ViewChildren(AddressComponent) addressComponents: QueryList<AddressCo ...

Learn how to showcase a predetermined option in an HTML select element using Vue.js and Minimalect

I am currently utilizing Vue.js along with the Mininmalect HTML select plugin to showcase a list of countries by their names and values, where the value represents the 2 digit country code. Successfully, I have managed to implement the plugin for selectin ...

"Encountered a Parsing Error: function keyword was an unexpected token in an Async Function using a more recent version of Node

In the process of working on a side project, I am utilizing node and firebase technologies. While I have successfully created regular functions and cloud functions, I encountered an issue when attempting to create an async function like so: async function ...

MUI's Checkbox with Radio Button feature functionality

In my project, I am looking to implement a Checkbox with radio button behavior inside an Accordion component. The challenge here is that only one item should be selected at a time. If one item is checked, it should automatically uncheck the previously sele ...

Can you place more than one Twitter Bootstrap carousel on a single webpage?

Latest Version of Twitter Bootstrap: 2.0.3 Sample HTML Code: <!DOCTYPE html> <html dir="ltr" lang="en-US" xmlns:og="http://opengraphprotocol.org/schema/"> <head> <link rel="stylesheet" type="text/css" media="all" href="reddlec/style. ...

The implementation of pushing inside a foreach loop is not correctly adding elements to

I have encountered an issue with running a foreach loop and adding values to an array in my code. The first foreach loop works as expected, adding values properly to the array. However, the second foreach loop seems to be malfunctioning as none of its valu ...

What is the best way to ensure that messages stay saved in my app for an extended

I am looking for a way to store messages sent through my small messaging app in a persistent manner. Currently, the messages are transferred from the front-end to a Node, Socket.io, and Express back-end. A friend recommended using Enmaps (), but unfortuna ...

Unfortunately, I am unable to transmit a cookie using the res.cookie method in Express

After setting up the route to send a JWT with a cookie, I'm unable to see it in my browser. Here's the code for the route: router.post('/signup', async (req, res) => { const { email, password } = req.body try { const ...

Dropdown menu not populating with options in AngularJS ngOptions

It's puzzling to me why the dropdown menu is not being populated by ng-options. Despite JSON data being returned from the service and successfully logged in the controller, ng-options seems to be failing at its task. <tr class="info"> <td ...

Error: doc.data().updatedAt?.toMillis function is not defined in this context (NextJs)

I encountered an error message while trying to access Firestore documents using the useCollection hook. TypeError: doc.data(...)?.updatedAt?.toMillis is not a function Here is my implementation of the useCollection Hook: export const useCollection = (c, q ...