Selective Array Reversing I have the following code that given an array, returns the reversed version of the array, reverse portions of the array.

For example

selReverse([1,2,3,4,5,6], 2)
//=&gt; [2,1, 4,3, 6,5]


function selReverse(array, length) {
  console.log(array)
  var resultArray = [];
    for (var i = 0, j=array.length ; i &lt; j; i += length) {
      resultArray.push.apply(resultArray, array.slice(i, i+length).reverse());
    }
  return resultArray;
}


This code passes the tests, but apparently, it's too slow. Is there a way to optimize it?
Don't put console.log calls in you functions unless there's a really good reason to. In this case, you're just printing the input, which is pretty pointless. It can also contribute greatly to the function's running time, since printing a large array isn't exactly free (a lot depends on how the runtime handles output)
You can simplify the code. You can do without slicing, reversing and applying chunks of the array


I'd just use two for-loops:

function selReverse(array, chunkSize) {
  var output = [],
      l = array.length;

  for(var i = 0 ; i &lt; l ; i += chunkSize) {
    var start = Math.min(i + chunkSize, l) - 1;
    for(var j = start ; j &gt;= i ; j--) {
      output.push(array[j]);
    }
  }
  return output;
}


Edit: The code above doesn't work, but I thought it was due to very large inputs or something, but that's not the case.

The simple solution is basically, that the for loop - both in my code and the original code - goes into an infinite loop if the chunkSize is zero. This works, though:

function selReverse(array, chunkSize) {
  var output = [],
      l = array.length;

  if(chunkSize === 0) return array.slice(); // could also do &lt;= 0 to be safer

  for(var i = 0 ; i &lt; l ; i += chunkSize) {
    var start = Math.min(i + chunkSize, l) - 1;
    for(var j = start ; j &gt;= i ; j--) {
      output.push(array[j]);
    }
  }
  return output;
}


Since it's got nothing to do with large inputs, I imagine the original code works just as well, as long as it too checks for the chunkSize.