Utilizing recursion and the reduce method for calculating the total of an array elements

Exploring the idea of a recursive function to sum up an array.

Here's the array structure I'm experimenting with: [[[1, 2, [[3], 4]], 5, []]]

As I delve into learning, I decided to implement it using reduce... and it's been quite successful, albeit with occasional hiccups:

const sumItems = function(array) {
  return array.reduce(function(acc, x) {
    return acc + (Array.isArray(x) ? sumItems(x) : x);
  }, 0);
};

Looking to streamline it further, I attempted a more concise approach:

const sumItems = function(array) {
  const reducer = (acc, x) => (acc || 0) + (Array.isArray(x) ? sumItems(x) : x);
  return array.reduce(reducer);
};

However, this approach didn't quite yield the expected results. Despite multiple attempts and console logging, I ended up with output like this:

[ [ 1, 2, [ [Array], 4 ] ], 5, [] ]

An intriguing discovery indeed...

If anyone has insights on how to address this issue, I'd appreciate the guidance. Could I be missing a key concept in JavaScript?

Thanks for your input

Answer №1

Make sure to provide an initial value in the reduce method. If the first element is an array, it may fail and return NaN in certain iterations. In the next iteration, acc || 0 will result in 0 because NaN is a falsy value.

var data = [
  [
    [1, 2, [
      [3], 4
    ]], 5, []
  ]
]

const sumItems = function(array) {
  const reducer = (acc, x) => acc + (Array.isArray(x) ? sumItems(x) : x);
  // -now || is not needed --^^^^----- since we'd added initial value so it will be always a number
  // for treating non-digit or non-array value you can replace `x` with `+x || 0` for treating it as `0`
  
  return array.reduce(reducer, 0);
  // ---- initial value-------^^^----
};

console.log(sumItems(data))

Answer №2

Make sure you provide an initial value to the reduce function instead of attempting to use || 0 with the acc parameter inside the reducer function.

const reducer = (acc, x) => acc + (Array.isArray(x) ? sumItems(x) : x);
const sumItems = array => array.reduce(reducer, 0);
//                                              ^

If you don't pass an initial value to reduce, it will encounter issues when dealing with empty arrays.

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

AngularJS enables box to smoothly slide up and down when hovered over

I am attempting to create a div that will overlay an image on hover with a slide up and slide down effect. Can anyone provide guidance on how to achieve this without relying on jQuery? I would prefer to utilize only AngularJS in my application. Here is a ...

Issue with Wicket: unable to generate sound for resource paths

I am having some trouble with a path in my wicket project. There is a sounds folder located within the Web Pages directory. Within my JavaScript code, I am using the following path to play sounds: audioElement.setAttribute('src', 'sounds/s ...

What is the best way to comprehend this asynchronous exercise with async/await?

Currently, I am working on some exercises related to async/await, and I seem to be stuck on the following problem: The function ​​opA​ should be executed before ​opB​, and ​opB​ should be executed before ​opC​. Arrange the function call ...

transferring information from a JavaScript variable to an EJS variable

I am currently storing a value in the 'items' variable within a script tag in an HTML document. However, I now need to pass this data from 'items' to the back end in order to store it in a database. I attempted to make 'selectedTea ...

Utilizing React hooks to import an array of objects in JSON format

I spent an entire day trying to incorporate categories from a JSON file into my React project using hooks, but I haven't had any success yet. I'm really hoping someone can assist me with this task. Below is a snippet of the JSON structure: { &quo ...

What steps can I take to resolve the Angular JS error message: [$injector:unpr]?

index.html <!DOCTYPE html> <html lang="en" ng-app="myApp"> <head> <meta charset="UTF-8"> <title>Angular JS</title> <script src="lib/angular.min.js"></script> ...

The callback function does not get invoked when using JSONP

Learning jsonP has been a challenge for me as I am relatively new to it. I have done my research by reading various articles but when trying out a simple example, the callback function fails to execute. Surprisingly, there are no errors or exceptions logge ...

Using the class attribute for Pagedown instead of the id keyword

I am utilizing Pagedown, which necessitates giving the id wmd-input to a textarea. This requirement is outlined in Markdown.Editor.js as follows: function PanelCollection(postfix) { this.buttonBar = doc.getElementById("wmd-button-bar" + postfix); ...

Hold off on addressing the nested loops within a TypeScript subscription

Goal: Ensure all nested loops complete processing before returning final value. Problem: Final value returned prematurely, before completion of loop processing. In the code snippet below, I am sending paramListToComplete to a data service for creating a ...

Is it possible to swap a <div> element with the content of another HTML page using the .innerHTML method?

I am currently working on a project that involves loading different webpages into a <div> on my page once specific links are clicked. I came across a thread about using jQuery for this purpose, but I'm not familiar with it. Is there a way to ach ...

Guide on redirecting the user to the "notFound" page within the getServerSideProps function in Next.JS whenever an incorrect params.id is provided

export const getServerSideProps = async ({ params }) => { const res = await fetch( `https://pixabay.com/api/?key=${process.env.API_KEY}&id=${params.id}` ); const { hits } = await res.json(); if (!hits) { return { notFound: tr ...

Resolving Node.js Absolute Module Paths with TypeScript

Currently, I am facing an issue where the modules need to be resolved based on the baseUrl so that the output code is compatible with node.js. Here is my file path: src/server/index.ts import express = require('express'); import {port, database ...

Tips for moving a polygon while dragging a marker within its boundaries

Currently, I have a map displaying polygons and markers, accompanied by a sidebar featuring tool buttons (similar to the setup showcased in this demo: ). Each marker on my map is connected to the respective polygon stored in my database. When I utilize the ...

Uh-oh, the Next.js fetch didn't go as planned. The error message

Currently, I am using Next.js 14 for my project. Suddenly, there has been an issue where some images are not loading on my local setup. However, the images load fine on the preview and production branches on Vercel. Upon checking my console, I noticed th ...

Is there a way to embed HTML code within a JavaScript variable?

Embedding HTML code within Java Flow can be quite interesting For instance: Check out this JSFiddle link And here's how you can incorporate it into your script: widget.value += ""; Generating a Pro Roseic Facebook POP-UP Box through Widg ...

Monitoring the progress of file uploads within itemView

In the process of developing an application using Marionette/Backbone, I have successfully implemented file uploads over an AJAX call. Now, I am looking for a way to provide users with feedback on when they can select the uploaded file and proceed with mod ...

What is the best way to update the class names of all JSX elements within a component when new props are received?

I am currently working on developing a container component that will store filter data and pass it down to another component responsible for rendering the filtered list. The data for this container component is sourced from a parent component. The filterin ...

What is the process for generating a JSON response in a PHP file?

My goal is to receive a JSON response on my second server with the domain example.com. The file getit.php on that server contains: $arr = array('antwort' => 'jo'); echo json_encode($arr); However, when attempting to retrieve this ...

What is the method for including a placeholder with sequential numbering?

When I click on the "Add String" button, it clones the first table row with an input in the table and adds it to the table. I also need to add a +1 number in the placeholder of the copied element. How can I determine the last placeholder before copying and ...

Exploring Heroes in Angular 2: Retrieving Object Information by Clicking on <li> Items

Currently, I am delving into the documentation for an angular 4 project called "Tour of Heroes" which can be found at https://angular.io/docs/ts/latest/tutorial/toh-pt2.html. <li *ngFor="let hero of heroes" (click)="onSelect(hero)">{{hero.name}}< ...