Calculate the total of array elements by using recursion, even if they are strings

Need to create a function that will return the sum of all elements in an array, but if the array contains strings like

["a","b","c"] // output : abc    

Currently, I have this code:

 function calculateSumRecursion(array) {
          //your code
          if (array.length === 0 ) {
            return 0
          }
          
      return array[0] + calculateSumRecursion(array.slice(1))
    }

I am able to calculate the sum of numbers using recursion, however, when it's an array of strings like

array = ["a","b","c"]

it returns

// abc0

due to the if statement.. Is there a way to make it so that

if (array.length === 0) return nothing instead of a 0 (that only works for arrays of numbers)?

Answer №1

To optimize the function, it is recommended to promptly return the only value in the array when its length is 1 instead of waiting until the length reaches 0. This approach ensures that you are always summing compatible types, whether they are numbers or strings. Additionally, don't forget to include a test for an empty array to handle such scenarios appropriately. In this scenario, the expected output is 0.

function calculateSumRecursion(array) {
  if (array.length === 0) {
    return 0;
  }
  if (array.length === 1) {
    return array[0];
  }
  return array[0] + calculateSumRecursion(array.slice(1))
}

console.log(calculateSumRecursion([1, 2, 3, 4, 5]));
console.log(calculateSumRecursion(['a', 'b', 'c']));
console.log(calculateSumRecursion([]));

Answer №2

const nums = [5, 4, 3, 2, 1] // result : xyz
let total = calculateSumRecursive(nums);

function calculateSumRecursive (nums) {
    return nums.length ? nums.pop() + calculateSumRecursive(nums) : 0;
}

Splice approach

const nums = [5, 4, 3, 2, 1] // result : xyz
let total = calculateSumRecursive(nums);

function calculateSumRecursive (nums) {
    return nums.length ? nums[0] + calculateSumRecursive(nums.slice(1)) : 0;
}

Answer №3

Update the code by replacing return 0 with return "" in order to include an empty string in the total.

Answer №4

If the array is empty, make sure to return an empty string rather than zero.

When working with string operations, it is more appropriate to return an empty value, which can be represented as "".

function calculateSumRecursion(array) {
  return array.length === 0 ? "" : array[0] + calculateSumRecursion(array.slice(1));
}

Answer №5

Here's a streamlined method for achieving the same outcome:

    const sumArray = (arr) => {
        let total = arr[0];
        for (let j = 1; j < arr.length; j++) {
            total += arr[j];
        }
        return total;
    }

Answer №6

When reaching the base case in recursion, make sure to return an empty string instead of a value. Simply update your return 0 statement to return ''.

const array = ['a', 'b', 'c'];
function calculateSumRecursion(array) {
  if (array.length === 0) {
    return '';
  }
  return array[0] + calculateSumRecursion(array.slice(1));
}

console.log(calculateSumRecursion(array));

If you need to handle numbers as well, remember to check for array lengths of both zero and one.

const array = ['a', 'b', 'c', 'e'];
const array2 = [];
const array3 = [1, 2, 3];

function calculateSumRecursion(array) {
  const rec =
    array.length === 1
      ? array[0]
      : array.length >= 1 && array[0] + calculateSumRecursion(array.slice(1));
  return array.length === 0 ? 0 : rec;
}

console.log(calculateSumRecursion(array));
console.log(calculateSumRecursion(array2));
console.log(calculateSumRecursion(array3));

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

Are there any concerns with memory usage when using static in React Native?

Considering using static in my react-native project but unsure about memory usage. Concerned if it will consume extra memory or potentially cause memory leaks. ...

Troubleshooting the 'npm ERR! ERESOLVE could not resolve' and 'peer dependency' issues: A guide to fixing the ERESOLVE error in npm

After several days of encountering an error while trying to set up a website for remote training, I have not been able to find a solution that fits my needs. Requesting your help to resolve the issue and get the site live on Vercel. Thank you in advance f ...

Customize Highcharts axis properties after adding additional series to the plot

When working with highcharts, I utilize the xAxys and yAxis properties to format the inserted data. The code used is the same for both axes, so I'll provide an example for one of them: $('#containers').highcharts({ .... .... yAxis: { ...

What causes the vertical scroll bar to shift on its own?

I'm puzzled by the behavior of the vertical scroll bar when clicking on "Line 9" - it automatically moves to the top position and subsequent clicks don't affect it. Can someone shed light on why this happens and how to resolve it? I am using Fire ...

Assign false to all properties in the nested object with the exception of one

In order to manage the open/close state of my panel, I am using setState similar to the method described in this post. My goal is to only allow one panel to be open at a time, meaning there will be only one true value in the state. Here is the snippet of ...

the solution to resolving misaligned CSS divs

I am facing an issue with displaying 3 div cards that contain different sets of information. Despite setting them to display:grid and trying to evenly distribute the fractions, the divs are stacking awkwardly. JS fiddle demo <!--Main Background-- ...

Utilizing Selenium automation to navigate a website that features a custom jQuery plugin-checkbox functionality

Utilizing Selenium WebDriver along with JavaScript to automate the testing of a website that features a custom jquery plugin named "jcf" (JavaScript Custom Forms) for aesthetically pleasing forms. You can find more information about this plugin here. I am ...

Javascript code for identifying objects in an array with specific properties and values

I have a collection of objects. Each object contains a boolean property named available, along with various other properties. While I am aware that the available property is present, the rest of the properties are unknown. For example: var myObjects = [ ...

How do I utilize Ajax to compare the value selected from a drop down menu in a form with entries in my database, and retrieve the corresponding record/row to automatically fill in a form?

I have a drop-down menu where users can select an option. I need to match the selected value with the corresponding record in my database under the "invoiceid" column, and then populate a form with the associated data when a prefill button is clicked. Belo ...

Why does my jQuery code target all the text values?

Looking to grab a specific table cell number and multiply it by an input value on focusout, but having trouble with the selector grabbing all cells with "front" in the name. Check out the code below: jquery $(document).ready(function(){ $(".percent") ...

Discover how to iterate through an array following a map operation and generate a new array based on conditional statements

data.risk.scatterIndices.investments.map((el: any) => el.name) || [] I have a mapping function that generates an array like this: ["pension","realestate","balance","kupot"] This is the condition I want to use t ...

Transferring Data from Angular Application to Spring Server via Rest Implementation

I am currently facing an issue while attempting to upload a file using Angular and send it to my Spring-based REST backend. I followed the guidance provided in this resource for my Angular service implementation. However, two problems have arisen: The fir ...

Getting the device id in a web application built with React JS

Currently, I am working on creating a reactjs app and I have a requirement to restrict multiple device logins for one account. To achieve this, I need a unique and persistent ID assigned to each device. In addition, I want the user to remain logged in on ...

JQuery's find() method followed by length/size() is resulting in a return

I'm running into an issue with dynamically created divs. Here's how they are created: // Loop through and append divs to #result_main_search $("#result_main_search").append('<div class="singleresult_main_search"> <a href="http:// ...

Suggestions on coloring polyline segments according to the density of neighboring segments surrounding the specific polyline segment

Apologies for the lengthy title, but I am interested in developing a polyline heatmap that changes color based on the number of lines within a certain proximity. Here is an example of what I have in mind: https://i.sstatic.net/W2lox.jpg Are there any inn ...

Vue-Routes is experiencing issues due to a template within one of the routes referencing the same ID

I encountered an issue while developing a Vue application with Vue-routes. One of the routes contains a function designed to modify the background colors of two divs based on the values entered in the respective input fields. However, I am facing two probl ...

A-Frame's video and video sphere functionalities do not function properly on mobile and tablet devices

When using A-Frame, I've encountered issues with video and video sphere not auto playing. This is because mobile browsers typically require a user action to initiate video playback. I've tried implementing a click event to play the video, but it ...

Generating a bullet list from an array of objects

Looking to create an unordered list with vanilla JS, using an array of objects to populate the list. Struggling a bit on how to accomplish this. Here is my current code: let myObj = [ {name: "Harry Potter", author: "JK Rowling"}, {name: "Hunger Gam ...

Ordering and categorizing a JSON dataset

data = [ { name: "Alpha", set: 5, weight: 185 }, { name: "Alpha", set: 6, weight: 350 }, { name: "Bravo", ...

Electron application failing to initiate child process after relocation to new directory

After clicking a button in my application, a child process is initiated using the fork() function. This functionality works well when the app is bundled into an executable in the dist folder (via electron-builder). However, if I move the win-unpacked folde ...