1

When dealing with a recursive call within an array object, where I'm passing an array to a function and each proceeding call, I'd like the array argument to be n-1.

I normally use:

  • Array.prototype.shift
  • Array.prototype.pop

I have to call these methods the line before the recursive call. Check the example below.

Here is what I normally resort to:

function responseData(urls){
    if (urls.length-1){
        return;
    }
    http.get(urls[0], function(res) {
      res.setEncoding('utf8');
      var body = '';
      res.on('data', function(chunk) {
        body += chunk;
      });
      res.on('end', function() {
            console.log(body.toString());
            urls.shift(); // NOTICE THIS LINE
            printResponseData(urls);
      });
    });
}

Is there a cleaner alternative to this approach?

Can I eliminate using shift or pop that return values, to a method that will minimize the size of the array and return the newly minified array so I can pass this straight to my recursive call?

2
  • printResponseData(urls.slice(1)); Commented Feb 25, 2016 at 21:37
  • if (urls.length-1){ is weird. Did you mean if (urls.length==0){? Commented Feb 25, 2016 at 21:38

2 Answers 2

3

You can use the slice method to get a smaller array. It won't mutate the original argument, but rather create a new one.

To get an array without the first element, use

urls.slice(1)

To get an array without the last element, use

urls.slice(0, -1)
Sign up to request clarification or add additional context in comments.

Comments

0

I'm guessing this is what you mean?

printResponseData(urls.slice(1));

will skip the first element and give the rest to the end of the array

// or
printResponseData(urls.slice(0, -1));

will give from the start of the array to the penultimate element.

1 Comment

Just like what Bergi said!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.