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

extracting ng-repeat values and passing them to the controller

I have created a form that dynamically increases whenever the user clicks on the add sale button Here is the HTML code: <fieldset data-ng-repeat="choice in choices"> <div class="form-group"> <label for="name"> Qu ...

Guide to writing a Jasmine test case to verify Toggle class behavior within a click event

My directive is responsible for toggling classes on an element, and it's working as expected. However, I seem to be encountering an issue with the jasmine test case for it. // Code for toggling class fileSearch.directive('toggleClass', func ...

What is the best way to include numerous optional parameters within a single route in Express?

Been a huge fan of Stackoverflow and finally decided to ask my first question here! I've been working on a JavaScript Express project, trying to figure out if it's possible to achieve the desired functionality under a single GET request. Struggli ...

Utilize TinyMCE in your WordPress plugin

How can I integrate TinyMCE into my WordPress plugin? I have a textarea in the backend script that I would like to convert into a TinyMCE WYSIWYG editable field. Is there a method to achieve this? The following code snippet is not yielding the desired re ...

Utilizing Node and Express to transform an array into a "Object" Map

For my latest project, I decided to build a web application using Node Express for the backend and Vue for the front end. While working on it, I encountered an issue where an array in an object was being converted to a map when sent to Express via jQuery. ...

What is the best way to display a list of lists in a React application?

I have a collection of lists containing data that I need to display on the view. The data: { "blocks_content": [ [ " Bakery", " Company GbR", ], [ ...

How can the hreflang tag be used correctly in a React application that supports multiple languages?

I have a React application with 3 pages(routes) and I support 2 languages (English and Spanish). Should I insert the following code into the <head></head> section of the public\index.html file like this? <link rel="alternate" ...

How can I achieve a similar functionality to array_unique() using jQuery?

When I select values from a dropdown, they are stored as an array like ["1","2","3"] Upon each change, the code below is executed to generate a new array based on the selected values: $('#event-courses-type').on('change', function(){ ...

What is the best way to transform a date such as '2021-06-01T11:17:00-07:00' into the corresponding date and time for a specific location (New Delhi) using JavaScript?

How can I convert a date in the format '2021-06-01T11:17:00-07:00' to ISO standard? What does this format represent? let date = new Date('2021-06-01T11:17:00-07:00'); console.log(date.getHours() + " :" + date.getMinutes()); I ...

Tips for sending a set to a directive in angular.js?

Forgive me for my confusion. I am passing the name of a collection to my directive: <ul tag-it tag-src="preview_data.preview.extract.keywords"><li>Tag 1</li><li>Tag 2</li></ul> This is how the directive is defined: a ...

Utilize Content Delivery Network Components in Conjunction with a Command Line Interface Build

As we progress in building our Vue applications, we have been using the standard script tag include method for Vue. However, as we transition from jQuery/Knockout-heavy apps to more complex ones, the maintenance issues that may arise if we don't switc ...

When my script is located in the head of the HTML page, I am unable to

My goal is to make my JavaScript code function properly when I insert it into either the head or body elements of an HTML document. Let's look at some examples: First, I insert the script into the body as shown in this example (works correctly): ...

Guide to specifying an explicit return type annotation for a recursive closure with JSDoc

In a project that utilizes vanilla JavaScript and type checking with tsc through JSDoc annotations, I have encountered a challenging use case. There is a function that returns another function, which may recursively call itself while also reassigning certa ...

Utilizing Node.js and express to promptly address client requests while proceeding with tasks in the nextTick

I am looking to optimize server performance by separating high CPU consuming tasks from the user experience: ./main.js: var express = require('express'); var Test = require('./resources/test'); var http = require('http'); va ...

Developing in Node.js involves setting a specific timezone while creating a date

I feel like I'm overcomplicating things here. My server is running on nodejs, and the front-end is sending me an offset. What I need is to determine the UTC equivalent of yesterday (or today, or last week) based on this offset. Currently, my code l ...

Finding all parent IDs from a given child ID within a nested JSON structure that contains children can be achieved by recursively

function loadKendoTreeView() { if ($("#treeview").data("kendoTreeView") != null) { $("#treeview").data("kendoTreeView").destroy(); $("#treeview").empty(); } var jsonData = [{ "Id": "239297d8-5993-42c0-a6ca-38dac2d8bf9f", ...

Troubleshooting Query Param Problems in EmberJS Route Navigation

("ember-cli": "2.2.0-beta.6") A search page on my website allows users to look for two different types of records: Users or Organizations. The URL for this search page is /search and I have implemented query parameters to maintain the state and enable ba ...

How to prevent all boxes in jQuery from sliding up at the same time

I am encountering an issue with 36 boxes where, upon hovering over the title, the hidden text below it should slide up. However, all 36 boxes are sliding up simultaneously instead of just the one being hovered over. Below is the script I am currently using ...

The JavaScript-rendered HTML button is unresponsive

I have a JavaScript function that controls the display of a popup window based on its visibility. The function used to work perfectly, with the close button effectively hiding the window when clicked. However, after making some changes to the code, the clo ...

The function is not triggered when the select tag is changed

I'm currently working on implementing a drop-down menu using the <select> element in HTML. Here is the code snippet I have so far: <select id="Parameter1" onchange="function1()"> <option value = "0105" name = "Frequency">Frequency ...