What could be the reason for the empty array returned by the combinationSum function in Javascript?

The combinationSum function is returning an empty resultArr. When checking the ds array with console.log, it shows the correct answer, but for some reason, the final output array ends up being [[],[]].

var combinationSum = function(candidates, target) {
    const resultArr = []
    function combinationSumHelper(idx, candidates, ds, target){
        if(idx === candidates.length){ // base case
            if(target === 0){
                console.log(ds) *// The console log here displays the right answer, but somehow the resultArr returned by combinationSum remains empty*
                resultArr.push(ds)
            }
            return
        }
        if(candidates[idx] <= target){
            ds.push(candidates[idx])
            combinationSumHelper(idx, candidates, ds, target - candidates[idx])
            ds.pop()
        }
        combinationSumHelper(idx+1, candidates, ds, target)
    }
    combinationSumHelper(0, candidates, [], target)
    return resultArr
};

console.log(combinationSum([2,3,6,7], 7))

OUTPUT: [ [], [] ]

EXPECTED OUTPUT: [[2,2,3],[7]]

STDOUT: [ 2, 2, 3 ] [ 7 ]

Answer №1

If you are searching for a specific output, the code provided below will help in achieving it:

var combinationSum = function(candidates, target) {
    const resultArr = []
    function combinationSumHelper(idx, candidates, ds, target){
        if(idx === candidates.length){ // base scenario
            if(target === 0){
                console.log(ds) *// This line gets the correct answer but the resultArr returned by the combinationSum function remains empty.*
                resultArr.push([...ds])
            }
            return
        }
        if(candidates[idx] <= target){
            ds.push(candidates[idx])
            combinationSumHelper(idx, candidates, ds, target - candidates[idx])
            ds.pop()
        }
        combinationSumHelper(idx+1, candidates, ds, target)
    }
    combinationSumHelper(0, candidates, [], target)
    return resultArr
};

console.log(combinationSum([2,3,6,7], 7))

The issue at hand is related to the if condition with ds.push and ds.pop which alters your array and the final outcome.

To resolve this, modifying the code to resultArr.push([...ds]) allows creating a copy of your array to prevent further mutations.

Upon executing this code, the generated output reveals: [[2, 2, 3], [7]]

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

In the production mode, Webpack doesn't compile any code

I recently followed the typescript guide at https://webpack.js.org/guides/typescript/ After running webpack in "production" mode, I noticed that it emitted very minimal output. Below is the code from my src/index.ts file: export function foo() { return ...

A beginner's guide to integrating Socket.io with Express.JS using the Express application generator

Currently, I am attempting to utilize Socket.io alongside Express.JS by using the Express application generator. While searching for solutions, I came across some helpful advice on how to achieve this (check out Using socket.io in Express 4 and express-gen ...

A comparison of parent and child components

To implement a child-parent component relationship in Angular, first create two JSON files: parent.json and child.json. The parent.json file should contain the following data: "Id":10001, "name":"John" "Id":10002, ...

Ordering request parameters in OAuth2 URL with npm passport can be achieved by following a specific method

I have successfully utilized Oauth2 strategies like Github and Twitter to log in to a web application using npm passport. Now, I am interested in logging in using the new global id authentication. You can explore it here ; it's really amazing. Whil ...

access the ckeditor within the frame

I have a CKEditor in a frame and am experiencing an issue. When I try to console log from the browser, it won't work until I inspect near the frame and perform the console log again. [This is the CKEditor] https://i.stack.imgur.com/fWGzj.png The q ...

Leveraging icons with Bootstrap 4.5

I am currently exploring how to incorporate Bootstrap 4.5 icons using CSS. Do you have any examples of code that could guide me on how to achieve this? I am specifically interested in understanding the required CSS declarations that would allow me to use t ...

Ways to confirm the validation of radio buttons in a form and implement CSS

I am having trouble adding validation to a form with radio buttons displayed as labels. I want to show a red border around the radios/labels or outer div when a radio button hasn't been checked before the user submits the form. I have attempted this ...

jQuery Filter for Page Content - choose specific text within paragraphs and clickable links

I recently created a page search filter using Bootstrap 5, but it seems to only display text content and not any content enclosed within the a tags. You can check out the JS Fiddle link provided below for reference: https://jsfiddle.net/mfen723/rozy16pt/1 ...

Conceal Profile Field When User Metadata is Empty - WordPress

Hey everyone, hope you're all having a great evening! I'm looking to hide a profile field when the user meta is empty. For instance, in the image provided, I want to conceal the billing_ateco row because the billing_ateco field is blank. I&apo ...

How can I incorporate arithmetic operators within a function in EJS?

Currently, I am developing an express app that includes a booking form using ejs with added functionality for payment processing. In the code, I have a select tag where the selected text is stored in a variable. Although console logging shows the value co ...

Guide to selecting text within an unordered list on an HTML webpage without a distinctive identifier with Python Selenium

I am looking to automate the selection and clicking of the text 'Click Me Please' within a hyperlink using Python Selenium. The main challenge is that there is no distinct identifier for this item as it is nested within a list. The specific HTM ...

Encountered an invalid prop type error while employing CSSTransition

Encountering an issue with the implementation of CSSTranstion for React. The purpose is to animate the mobile menu in a small application. Everything was functioning properly until the inclusion of the react-transition-group package, specifically using < ...

Utilizing jq for transforming a collection of dictionaries into an organized array

I have been struggling to extract formatted data from an AWS DynamoDB scan command. Here is a sample item from the DynamoDB table: { "labels": { "Category": [ "Data", "EMR" ], "Environment": "NonProd", "Severity": "Critical" ...

Click here to get the button click link

Is there a method to obtain the link of a button click on a website? This is the Website and it features a play button. I am looking for a way to capture the link triggered by clicking the play button so that the audio starts playing automatically each t ...

Iterate through the list retrieved from the backend

I have a list coming from the backend that I need to iterate through and hide a button if any element in the list does not have a status of 6. feedback The response returned can vary in length, not always just one item like this example with 7 elements. ...

Guide to Displaying HTTP POST Request Response on Pug Template

Whenever a user interacts with the form, I initiate an HTTP POST request to the database server. Subsequently, the database server sends a POST request back to the user's server. The issue I am facing is the inability to display this database result ...

Which is the better choice for accessing and manipulating JSON files – using Ajax or the Node fs module?

When storing quiz questions using JSON data, should I use vanilla AJAX or Node.js file system to read the file? I am planning to develop a website where users can create quizzes and save them as JSON. I intend to utilize the Node.js fs module to save the ...

Fetch data in JSON format from a specified URL

I have been attempting to fetch a JSON from a specific URL. Here is my current code snippet: <script> var co2; $(document).ready(function(){ alert("0"); $.getJSON(url,function(result){ var jsonObject = result; alert(result); ...

React - Utilizing Secondary Prop Value in Material UI Node Components

I've been working on streamlining my code and am wondering about the best way to pass an additional value using props while fetching data from the backend. I'm utilizing material UI's Autocomplete with the PERN stack. Everything is functioni ...

Enhance your HTML audio player with added timeline functionality

I'm currently working on incorporating an HTML audio player into my project. I've managed to get the play/pause functionality to work, but now I'm stuck on adding a timeline feature. Additionally, I'm not sure how to implement the play/ ...