Discovering the total of elements within any given JavaScript array

I have a complex array structure and I am looking for a way to calculate the sum of all numbers without using Array.isArray method:

let arr = [[1, 2, 3, [4, 5, [6, 7]]], [8, [9, 10]]]; 

An ideal solution would transform the array like this:

let arr = [[1, 2, 3, 4, 5], [6, 7, 8], [9, 10]]; 

for (let i = 0; i < arr.length; i++) { 
   for (let j = 0; j < arr[i].length; j++) { 
      console.log(arr[i][j]);
   }
}

If you have any suggestions on how to accomplish this task, please share them with me.

Answer โ„–2

To achieve this, you can utilize the Array#flat method along with Array#reduce to flatten the array or alternatively verify the type of the value using the instanceof operator.

function calculateSum(array) {
    return array.flat(Infinity).reduce((sum, value) => sum + value, 0);
}

function findTotal(array) {
    let total = 0;
    for (const value of array) {
        total += value instanceof Array
            ? findTotal(value)
            : value
    }
    return total;
}

let numArray = [[1, 2, 3, [4, 5, [6, 7]]], [8, [9, 10]]];

console.log(calculateSum(numArray));
console.log(findTotal(numArray));

Answer โ„–3

To accomplish this task, you can utilize the power of the lodash library:

var _ = require("lodash");
var nestedArray = [[1, 2, 3, [4, 5, [6, 7]]], [8, [9, 10]]];
flatArray = _.flattenDeep(nestedArray);
sum = flatArray.reduce((accumulator, currentValue) => accumulator + currentValue, 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

What could be the reason why the toggle active function is not functioning as expected in this code

I need some guidance on how to properly share code on stackoverflow. For the complete code, you can view it on Codepen: Codepen const hamburger = document.querySelector(".hamburger"); const navMenu = document.querySelector(" ...

I am looking to extract only the pairs from the given array, which is represented as `pairsByIndexRaw = [[0, 3], [1, 2], [2, 1], null, [1], false, "whoops"];`

I have a specific array that needs some filtering done. My goal is to remove items that are null, false, and the string "whoops" using JavaScript's filter method. let pairsByIndexRaw = [[0, 3], [1, 2], [2, 1], null, [1], false, "whoops"]; ...

The plugin "react" encountered a conflict while trying to sync with both the "package.json" and the "BaseConfig" files

Whenever I open Terminal in my react folder and try to start the react app using npm start, I always end up encountering an error on the browser. The error message states that the "react" plugin is conflicting between two paths: "package.json ยป eslint ...

Guide on Importing All Functions from a Custom Javascript File

As a beginner in learning Angular, I am faced with the task of converting a template into Angular. However, I am struggling to find a solution for importing all functions from a custom js file into my .component.ts file at once. I have already attempted t ...

Utilize a randomized dynamic base URL without a set pattern to display a variety of pages

I am intrigued by the idea of creating a dynamic route that can respond to user-generated requests with specific files, similar to how Github handles URLs such as www.github.com/username or www.github.com/project. These URLs do not follow a set pattern, ma ...

Is there a more efficient method for storing JSON values as an Array in my code?

Let me share my approach: <script> function games(){ document.write("loading"); $.ajax({ url: "http://allencoded.com/test3.php", dataType: 'json', success: function (data) { var homeTeams = new Array(); for (var i ...

Learn how to successfully carry on with event.preventdefault in JavaScript

Is there a way to create a modal that prompts the user to confirm if they want to leave the page without committing changes? These changes are not made within a <form> element, but rather on a specific object. I've attempted to use both $route ...

Is it possible to interchange rows and columns in a 2D structured array?

I'm looking for a way to interchange both the columns and rows of a 2D struct array. Currently, I have code that can switch rows like this: #define N 9 typedef struct { char value; bool editable; } CELL; int main(){ CELL **grid = (CELL * ...

What is the procedure for utilizing Javascript to redirect a user on a website back to the login page if necessary?

Is there a way to redirect a website user back to the login page if they try to access a secure page without logging in first? I'm looking to implement this using JavaScript and cookies. Any suggestions or ideas on how to achieve this seamlessly for t ...

Issue with Masonry layout not adjusting to change in window size

Something seems to be fixed on displaying four rows, no matter the size of the window. Previously, it would adjust to three rows or fewer as the browser was resized. I recently played around with columnWidth, but reverting it back to 250 doesn't seem ...

Ways to verify if a variable holds a JSON object or a string

Is it possible to determine whether the data in a variable is a string or a JSON object? var json_string = '{ "key": 1, "key2": "2" }'; var json_string = { "key": 1, "key2": "2" }; var json_string = "{ 'key': 1, 'key2', 2 } ...

What are the limitations of sorting by price?

One issue I am facing is that the sorting functionality in the sortProductsByPrice (sortOrder) method doesn't work properly when products are deleted or added. Currently, sorting only applies to products that are already present in the this.products a ...

Utilize the 'Save and add another' feature within a bootstrap modal

Hello everyone, this is my first time seeking assistance on this platform. If any additional information is required, please do not hesitate to ask. Currently, I am working with JavaScript in combination with the handlebars framework. Within a bootstrap ...

Having trouble integrating Backbone-relational with AMD (RequireJS)?

I'm struggling with my Backbone router and module definitions in CoffeeScript. Can someone help me troubleshoot? // appointments_router.js.coffee define ["app", "appointment"], (App) -> class Snip.Routers.AppointmentsRouter extends Backbone.Rout ...

Excruciatingly tardy performance from Node, Apollo, and Sequelize (over 7 seconds)

Although I'm more comfortable with Laravel, I am experiencing a delay of approximately 7.2 seconds when running a single query in Apollo Server for around 300 items. The resolver code provided below seems to be fairly straightforward and only involves ...

The styles order definition in the Material-UI production build may vary from that in development

When using material-ui, an issue arises in the production build where the generated styles differ from those in development. The order of the material-ui styles in production does not match the order in development. In DEV, the material-ui styles are defi ...

Error occurred during conversion from an array to a string

I'm facing an issue with my query that extracts a list of IDs stored in an array, and I need to search another table using those IDs. I attempted to use implode function to convert the IDs into a string for a where clause, but I keep encountering an e ...

What steps should I take to ensure that the <select> tag is compatible with Microsoft Edge?

Currently, I am working on editing jsp files that utilize struts1. <html:select property="someProperty" style="width:110;height:110" styleClass="someClass"> However, when viewing it in Microsoft Edge, I noticed that the drop-down menu already ...

Angular UI Bootstrap collapse directive fails to trigger expandDone() function

I am currently utilizing UI Bootstrap for Angular in one of my projects, and I have developed a directive that encapsulates the collapse functionality from UI Bootstrap. Here is how it looks: app.directive( 'arSection', ['$timeout', fu ...

Leveraging Selenium to dismiss a browser pop-up

While scraping data from Investing.com, I encountered a pop-up on the website. Despite searching for a clickable button within the elements, I couldn't locate anything suitable. On the element page, all I could find related to the 'X' to cl ...