What is the best way to sum the numbers in this code snippet?

I'm trying to iterate through an array called arr = [[1,2],4] using for loops to access the numbers. However, I've noticed that I can't seem to add the last number for some reason. Can anyone explain why this is happening?

    let arr = [[1,2],4];       
    let total = 0;
        
    for(let i = 0; i < arr.length; i++) {
       for(let j = 0; j < arr[i].length; j++) {
          total += arr[i][j];
       }
    }
    console.log(arr.length)  // shows length = 2
    console.log(total);      // shows total = 3

Answer №1

The challenge you are facing is due to the fact that your array contains not only arrays but also single numbers and nested arrays. This causes an issue where your inner loop cannot iterate over the number 4 because it is not an array (and therefore does not have a .length property).

let arr = [[1,2],4];
// no issues-^   ^-- no `.length` property  (inner for loop won't run)

To solve this problem, you can utilize a recursive function. When encountering a nested array, you can recursively call your function to calculate the sum for that specific array.

Here's an example along with code comments:

function sumNums(arr) {
  let total = 0;
  for (let i = 0; i < arr.length; i++) {
    if(Array.isArray(arr[i])) { 
      total += sumNums(arr[i]);
    } else {
      total += arr[i]; 
    }
  }
  return total;
}

let arr = [[1,2],4];
console.log(sumNums(arr)); // 7

You can also achieve the same result using a recursive call with .reduce():

const arr = [[1,2],4];
const result = arr.reduce(function sum(acc, v) {
  return acc + (Array.isArray(v) ? v.reduce(sum, 0) : v); 
}, 0);
console.log(result); // 7

Answer №2

In order to handle both array and number values, it is important to add a check before proceeding with the inner loop.

   if (!Array.isArray(arr[i])) {
      total += arr[i];
      continue;
   }

    let arr = [[1,2],4];       
    let total = 0;
        
    for(let i = 0; i < arr.length; i++) {
       if (!Array.isArray(arr[i])) {
          total += arr[i];
          continue;
       }
       for(let j = 0; j < arr[i].length; j++) {
          total += arr[i][j];
       }
    }
    console.log(arr.length)  // returns length = 2
    console.log(total);

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

Identify the absence of search results in an Ajax request to the search page before rendering the HTML content

I am attempting to retrieve JSON code from a page using the following PHP function: private function __ajax_admin_search($username = '') { $result = $this->admin_login->Admin_Username_Ajax($username); $count = count($result); for ...

What is the best way to animate elements so that they move in a circular motion?

My goal is to recreate the image shown in the picture: https://i.sstatic.net/z08II.jpg In case the image is blocked, you can view it here: https://i.sstatic.net/YYg4J.jpg The picture appears to have only one icon visible, but there are actually 4 icons. ...

Guide on creating an Iframe in HTML with JavaScript

Can someone help me troubleshoot why the following code isn't working to write an iframe into HTML using JavaScript? <html> <body> <script> document.write("<iframe width="560" height="315" src="https://www.youtube.com/embed/9Ow8 ...

Having trouble getting the Bootstrap modal form to submit when using Knockout's submit binding?

Check out my jsFiddle example by clicking here. I am currently working on a form within a bootstrap modal. The problem I'm facing is that the knockout submit binding doesn't get executed unless the user clicks on the submit input. It seems like ...

Angular error: Trying to assign a value of type ArrayBuffer to a string type

Is there a way to display a preview of a selected image before uploading it to the server? Here is an example in HTML: <div id="drop_zone" (drop)="dropHandler($event)" (dragover)="onDragover($event)"> <p>drag one or more files to ...

Challenges of performance in EmberJS and Rails 4 API

My EmberJS application is connected to a Rails 4 REST API. While the application is generally working fine, it has started to slow down due to the nature of the queries being made. Currently, the API response looks like this: "projects": [{ "id": 1, ...

Can CSS be used to communicate to JavaScript which media queries are currently in effect?

Is there a way for Javascript to detect when a specific CSS media query is active without repeating the conditions of the media query in Javascript? Perhaps something similar to an HTML data attribute, but for CSS. For example: CSS @media (min-width: 94 ...

The blur() function in -webkit-filter does not seem to function properly in Vue.js

I'm having trouble implementing the -webkit-filter: blur() property. I tried using "filter" instead, but it still isn't working. Could this be a limitation of Vue.js or are there any other solutions available? <template> <div class=&qu ...

Enhance the efficiency of traversing a lengthy list of comparisons within an array.filter method

I am struggling with finding an efficient method to filter out items from an array of objects based on two specific attributes matching those of the last 6 items of another array. Currently, I have a manual process in place which results in cumbersome and ...

Visual Basic Array Issue for Grade Book Project

Whenever I input scores for four tests (1, 2, 3, 3), everything works perfectly in calculating the total and average. However, if I input scores for tests greater than 3, which exceeds my array size, I encounter an error in the following function: Public ...

Encountered an issue while attempting to access a property from an undefined source

I am struggling with this code as I am unable to correctly split the JSON data. The error message I keep encountering is: TypeError: Cannot read property "cu_id" from undefined. Here is a snippet of the JSON data (since it's too large to di ...

Retrieve the boolean value associated with a checkbox

I inherited a project from another developer. The code is able to retrieve data from the text input fields in the form, but not from the checkbox inputs. The previous developer implemented these functions (among others): protected function getObjectStrin ...

Creating a personalized pivot-table using the WebDataRock Javascript library with a unique configuration based on a

I'm having trouble getting this demo to work with the "hierarchy" parameter. Even when I specify the parameter value, it seems to apply the condition to the entire hierarchy chain. "conditions": [{ "formula": "#val ...

Steps to implementing a function just before a form is submitted

Imagine a scenario where you have the following HTML form: <form action="myurl.com" method="post" id="myForm"> <input type="number" name="number" class="numberInput"> <input type="number" name="number"> <input type="submit ...

How can I manually set a date in Angular bootstrap datepicker?

Using the Angularjs Bootstrap datepicker has been a great experience, but I encountered a problem when attempting to select the date using JavaScript. How can I ensure that the selected date in the datepicker matches the date read from a specific object, s ...

Steps to dynamically populate dropdown menus based on the selected options from other dropdown menus

I am working on a project that involves two dropdown menus. The options for the first dropdown menu are stored in a file called constant.ts. Depending on the selection made in the first dropdown, the options for the second dropdown will change accordingly. ...

Numerous buttons activating a single modal component

I have an array called videos, which contains objects of the type Video (defined below). My goal is to create a functionality where clicking on a specific video button opens a modal containing information about that particular video. interface VideosInfo ...

Creating a line graph using chart.js and JSON dataset

I'm working on plotting a line graph using a JSON response from my MongoDB, but I keep encountering an error that indicates something might be wrong with my code structure. Here's what I have attempted: myurl = "/api/humidity" $(function() { ...

What steps should I take to ensure my clock stays in sync with my runTime function?

I am developing a mini digital clock project with the ability to mimic a physical clock. The clock is activated by using a power button to switch it on and display the current time. It should also be able to turn off and show an empty screen. However, th ...

Browse the string on the web browser

Is there a way for me to continuously read and capture a string as it is being written in the browser, retrieving its value every 5 seconds? I need to be able to monitor the changing value while it is being input. In PHP, I have the following code snippet ...