Why does JavaScript return NaN when combining arrays of different lengths?

Information: Hey, take a look at these 4 arrays, and then there's an array with those arrays nested inside. I'm using _.reduce to calculate the total length of all arrays combined. However, when I run the function with the array of arrays, I'm getting NaN instead of the expected result of 19.

Can anyone explain why this is happening? Your help is much appreciated!

var array1 = [[1],[2],[3],[4],[5]];
var array2 = ["a", "b"];
var array3 = [{name : "John"}, {age : 21}];
var array4 = [1,2,3,4,5,6,7,8,9,0];

var array5 = [array4, array3, array2, array1];

var arrayComboLength = function(array){
return _.reduce(array, function(a,b){
    return a.length + b.length;
});
}


console.log(arrayComboLength(array5));  --> // NaN

Answer №1

When using the reduce function, keep in mind that the first argument of the callback function is the accumulator. In this case, there seems to be an issue with accessing the length property of a number, which leads to a value of undefined. This then results in adding undefined to the lengths of other arrays in the calculation, ultimately leading to a final result of undefined.

var calculateArrayLength = function(array) {
  return _.reduce(array, function(accumulator, currentValue) {
    return accumulator + currentValue.length;
  }, 0);
}

This scenario closely resembles the example provided in the documentation available at http://underscorejs.org/#reduce

Answer №2

Every element in the array will undergo the counting function recursively. This recursive application also extends to scalar values within array4. It's important to note that scalar values do not possess a length.

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

Sorting functionality malfunctioning after dynamically adding new content using AJAX

Greetings to all, I have a question about my views. 1- Index 2- Edit In the index view, I have a button and AJAX functionality. When I click the button, it passes an ID to the controller which returns a view that I then append to a div. The Edit view con ...

Overflow issue occurs in react-bootstrap when a Table is placed within the Card.Body

Looking to design a responsive table with a row details section inside a card using react bootstrap. I have applied different colors to the sections for better visual understanding. However, I am facing an issue where the card body slightly overflows the ...

How to selectively disable buttons in a group using React

I am working with an array of data const projectTypeValues = [ { name: 'Hour', value: 'hour'}, { name: 'Day', value: 'day'}, { name: 'Session', value: 'session'}, { name: 'project', valu ...

The callback function for ajax completion fails to execute

My current framework of choice is Django. I find myself faced with the following code snippet: var done_cancel_order = function(res, status) { alert("xpto"); }; var cancel_order = function() { data = {}; var args = { type:"GET", url:"/exch ...

What is the best way to trigger an event from a child component to a parent component in

parent.component.ts public test(){ //some code..... } parent.component.html <app-child (eventfire)="test($event)"></app-child> In this scenario, the child component button is displayed within the parent component. However, there i ...

Determining the index of the minimum values using Numpy in Python

The code snippet below performs a function that divides values into chunks based on the specified indexes, index, within the array L_list. The function then calculates the minimum value between indexes 3-5, which is -5, along with its corresponding index. ...

What is the correct way to embed a script tag within a block of JavaScript code?

I'm currently working on a JavaScript code that needs to be executed inside an iframe. The goal is to insert a script tag within the JavaScript code and then append it to the parent body of the iframe. Below is the snippet of my code attempting to ach ...

I am experiencing difficulty in detecting variable changes within my $scope function

I'm encountering an issue where a variable isn't being updated in a $scope function when there's a state change event. Despite seeing the variable update in the event listener, it doesn't reflect in the function. The code snippet in qu ...

Encountered an Error: Trying to use a function that is undefined - While utilizing Jquery Tabs

Working on implementing Jquery Tabs using the "description" and "reviews" li tags as tabs. Testing it out here . Everything seems to be functioning correctly here Key Points: This is Wordpress Multi-Site setup. The issue occurs in certain folders or "si ...

Incorporating rows of different sizes into a 2D array list

I'm currently tackling the challenge of parsing a text file with a specific format and organizing it into a 2D array list where each object, instead of each line, has its own index. 5 1 a w e r s 5 2 d 6 f s d e a 3 6 7 1 32 2 f s 6 d 4 s h y 99 3 s ...

Encountering CORS issue despite employing a CORS library

Encountering a CORS error while attempting to deploy my project on render using expressjs and react. The project functions smoothly on localhost, but changing the URLs to match the website results in this error: Access to XMLHttpRequest at 'https:// ...

Obtain the form value upon submission without the need to reload the page

I am facing an issue where I have a form and I want to trigger the display of a div (in the same page) and execute a JavaScript function upon clicking submit, all without causing a page refresh. <form action="#" method="post" name= "form1" id = "form ...

Having trouble loading a local texture in Three.js while using it as a component in Vue.js

When I run a three.js animation as a component within Vue, it works perfectly fine when loading the texture from an external online resource. However, when I try to run it locally by loading the texture from a local path, it displays black with no error me ...

There is an array present with data filled in, but unfortunately, I am unable to retrieve specific elements

As I work on my WordPress 4.7.2 website, I find myself making an AJAX call. The PHP function handling this call returns an array using wp_json_encode(). When I view the data array in the success callback of the AJAX function, everything looks just as expec ...

When selecting a dropdown in Angular 5, the aria-expanded attribute remains unchanged and the 'show' class is not applied. This behavior is specific to Bootstrap dropdowns

Having an issue with the bootstrap dropdown in my Angular project. When I click on it, the dropdown-menu does not show up. The 'show' class is not being added to the dropdown and the 'aria-expanded="false"' attribute does not change to ...

Display <tr> tag when button is clicked without refreshing the page

I have a specific requirement to hide a certain tag initially. If the user clicks the forward button without selecting any radio buttons or checkboxes, the tag should be displayed and the page should not refresh. However, there seems to be an issue with ...

A Node.js middleware that logs a message just once

My nodejs express app serves a file that requires and loads css files, js files, etc. I have implemented a logging middleware that retrieves the client's IP address and logs it (after cross-checking with a JSON file containing malicious IPs). Due to t ...

Is it possible to assign multiple ID's to a variable in jQuery?

I am currently using a script for a slider known as Slicebox, and in order to have different image sizes for mobile and desktop views, I need to duplicate the feature on my website. Although it's not ideal, I really like this slider and want to explo ...

The issue with object alignment in the camera rotation is not properly centered in the Three.js framework

After bending two meshes into a circle to create a 3D marquee, I'm facing issues with centering them to the camera. For the full code, please visit https://jsfiddle.net/siiiick/1jh49e1u/ var text = "EXPRESS FREE SHIPPING WORLDWIDE OVER 200€ / ...

Can you explain the function of the "info_dialog" method within the Visual Studio 2010 JavaScript AutoComplete feature?

While working on javascript in VS2010, I noticed a method called info_dialog in the autocomplete dropdown list. This method is not present in any of my javascript files and I am unable to determine its origin or functionality. Can anyone provide some ins ...