Can you provide tips on using a recursive function to combine elements of the first array with elements of other arrays?

Let's consider the following scenario: I have an array

arr=[1,3,7,8];
The 1st call will yield: [4,8,9]
The 2nd Call will yield:[12,13]
The 3rd call will result in:[25]

How can this be achieved using recursion in JavaScript?

Answer №1

You need to consider 3 scenarios

  1. For an empty array, the result should be an empty array
  2. For an array with only one element, return the same array
  3. If the array has 2 or more elements, return a new array with each element added to the previous

const foo = ([x,...xs]) => {
  if (x === undefined)
    return []
  else if (xs.length === 0)
    return [x]
  else
    return foo(xs.map(y => x + y))
}

console.log(foo([]))        // []
console.log(foo([1]))       // [1]
console.log(foo([1,3]))     // [4]
console.log(foo([1,3,7]))   // [12]
console.log(foo([1,3,7,8])) // [25]

The function can be enhanced by separating concerns and creating helper functions

const add = x => y => x + y

const isEmpty = xs => xs.length === 0

const isNull = x => x == null

const foo = ([x,...xs]) => {
  if (isNull(x))
    return []
  else if (isEmpty(xs))
    return [x]
  else
    return foo(xs.map(add(x)))
}

console.log(foo([]))        // []
console.log(foo([1]))       // [1]
console.log(foo([1,3]))     // [4]
console.log(foo([1,3,7]))   // [12]
console.log(foo([1,3,7,8])) // [25]

Answer №2

It may seem unusual to tackle this problem recursively, but here's a unique approach -

function calculateTotal(numbers){
  // base case
  if(numbers.length === 1 || numbers.length === 0) {
    return numbers
  } else {
    return calculateTotal(numbers.slice(1).map(element => element + numbers[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

Achieve iframe resizing using only pure JavaScript, no reliance on jQuery required

I have a question about an iframe on my webpage. <iframe class="myframe" src="some_page.html" width="800px" height="600px" /> Is there a way to make this iframe resizable like the <textarea></textarea> tag? I prefer to achieve this wit ...

My custom function is not invoking the Firebase function createUserWithEmailAndPassword

The function createUserWithEmailAndPassword is not being triggered within the SignUpUser function when the onClick event occurs. However, it works when I use onClick={signUpUser(email,password)} import React from 'react'; import styled from &apo ...

Having Trouble Deploying NextJS Site on Gh-Pages Despite Using basePath and assetPrefix

I recently built a website using next.js that is functioning well locally. The code for this site can be found at: https://github.com/xpress-smoke-shop/website. Now, I am attempting to deploy a static HTML version of the site to the domain: To do this, I ...

I am struggling to retrieve the data from the Giphy API after making the initial AJAX request

I'm currently in the process of building a basic website that fetches random gifs from the Giphy API. This project is purely for practice, so I'm keeping the site very minimalistic. However, I've hit a snag when it comes to extracting data u ...

What is the best way to use form input to filter an Observable?

Within my component, I have declared the variable "countries$": countries$!: Observable<Country[]>; To populate this variable with data from this API, I use the following code in the "ngOnInit" lifecycle hook: ngOnInit(){ this.countries$ ...

When using React Router, make sure to set the navigation tab's style class to "active" if you are

I'm currently working on a React and react-router application that uses 2 nested routes to create a total of 3 routes: /, /about, /contact. When I click on the Links to navigate to each route, the tab on my navigation bar - which is located in the par ...

A secure method for dynamically adding a JavaScript file

In my lang folder, I store language variables for a website. To dynamically include the desired file based on the user's language selection, I use session variables. For example, if the user selects English, 'en' is stored in the lang variab ...

Navigating through a predetermined list of HTML pages with next and previous options

Hey there, I'm in a bit of a quandary at the moment. I've been searching on Google for quite some time now, but unfortunately, I can't seem to find what I'm looking for. Hopefully, you guys can lend me a hand. What I'm trying to d ...

How can I incorporate a feature in my Angular application that allows users to switch between different view types, such as days, using JavaScript

Greetings, community! I am currently utilizing version 5 of the fullcalendar library from https://fullcalendar.io/ in my Angular 9 application. I have noticed that the calendar offers various options to change the view type as shown below: https://i.stac ...

Finding and removing the replicated keys within a JSON array while also retrieving the corresponding JSON path

I have a JSON object that looks like this: {"response":{"result":{"Leads":{"row":[{"LEADID":"849730000000063017","SMOWNERID":"849730000000061001"},{"LEADID":"849730000000063015","SMOWNERID":"849730000000061001","HIII":"hello"},{"LEADID":"84973000000006 ...

The functionality of jQuery is limited when trying to implement the .has() method

I have a jQuery code snippet that I am having trouble with function removePreloader() { jQuery('ul.woocommerce-error').has('li').jQuery("#preloader").css("display", "hidden"); } This function is triggered by jQuery('form[nam ...

Tips for creating a console.log wrapper specifically designed for Angular2 using Typescript

Is there a way to create a custom global logging function in Angular 2 TypeScript project that can be used instead of console.log for services and components? I envision the function looking like this: mylogger.ts function mylogger(msg){ console.log ...

Error encountered: The fiber texture failed to load due to a component becoming suspended during the response to synchronous input

I'm encountering an issue while attempting to load a texture through the TextureLoader: const texture = useLoader(TextureLoader, '/textures/texture.png') The error message I receive from react is as follows: ERROR A component suspended w ...

Ensure that properties return arrays and nested dictionaries - CA1819

I am facing a challenge with four properties that need to return arrays, dictionaries, and lists. According to CA1819 guidelines, direct returns of these data structures should be avoided. However, returning copies of the arrays can have a significant perf ...

Listener of events that is modifying the incorrect label

Here's a JSfiddle link for you to check out. JS fiddle I am currently attempting to build a quiz using JavaScript, where the questions and answers will be sourced from JSON data. checkbox.addEventListener('change', function() { i ...

Managing field placement as the table height grows: tips and tricks

I am encountering an issue with my dynamic form. When I click on the add button, a new row is added to the table. However, once there are more than 6 rows added, the table height starts covering the fields. How can I go about setting this so that the field ...

Ways to boost an array index in JavaScript

I recently developed a JavaScript function that involves defining an array and then appending the values of that array to an HTML table. However, I am facing an issue with increasing the array index dynamically. <script src="https://cdnjs.cloudflare. ...

How can I simulate keyboard events in Angular using a button click?

I've included separate buttons for Ctrl+z and Ctrl+y functionalities. When these buttons are clicked, I want them to perform the respective undo and redo actions programmatically. Below is the code snippet for this functionality. undoText(event:MouseE ...

What is the reason for choosing the term "shadow" over "override" in JavaScript?

Despite my initial assumptions, I found myself unable to discover a definitive answer through numerous Google searches on this topic. This question pertains to the use of the class pattern in Ecmascript 6 and beyond. I initially believed that method over ...

What methods can be used to maintain the selected date when the month or year is changed in the react-datepicker component of reactjs?

At the moment, I am using the Month selector and Year selector for Date of Birth in the react-datepicker component within a guest details form. The current functionality is such that the selected date is highlighted on the calendar, which works fine. How ...