HelloWorld
HelloWorld

Reputation: 11257

Remove item in array recursive call pattern?

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:

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?

Upvotes: 1

Views: 922

Answers (2)

Jimi WIlls
Jimi WIlls

Reputation: 348

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.

Upvotes: 0

Bergi
Bergi

Reputation: 664640

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)

Upvotes: 3

Related Questions