最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How does this if-else statement inside a function work? - Stack Overflow

programmeradmin1浏览0评论

I've been pleting challenges on FreeCodeCamp and stumbled upon this solution for an algorithm. Can't prehend how the if else statement works here.

function chunkArrayInGroups(arr, size) {

  var temp = [];
  var result = [];

  for (var a = 0; a < arr.length; a++) {
    if (a % size !== size - 1)
      temp.push(arr[a]);
    else {
      temp.push(arr[a]);
      result.push(temp);
      temp = [];
    }
  }

  if (temp.length !== 0)
    result.push(temp);

  return result;
}

Why is temp = [] at the end of the else block?

I've been pleting challenges on FreeCodeCamp and stumbled upon this solution for an algorithm. Can't prehend how the if else statement works here.

function chunkArrayInGroups(arr, size) {

  var temp = [];
  var result = [];

  for (var a = 0; a < arr.length; a++) {
    if (a % size !== size - 1)
      temp.push(arr[a]);
    else {
      temp.push(arr[a]);
      result.push(temp);
      temp = [];
    }
  }

  if (temp.length !== 0)
    result.push(temp);

  return result;
}

Why is temp = [] at the end of the else block?

Share Improve this question edited Sep 28, 2018 at 14:15 Quentin 3,2991 gold badge16 silver badges33 bronze badges asked Sep 28, 2018 at 14:04 Peter PeachPeter Peach 1791 silver badge10 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 6

temp = [] means "reset the temp variable to an empty array"


in the if block, the arr[a] element is pushed at the end in the temparray.

in the else block, the same happens AND the whole current temp array is added at the end of the big result array of arrays, and the temparray is reset to the empty array.

Cannot say much more since there is not data or context written in your question. Hope this has answered your question.

The function divides an array into chunks of small arrays where the 'size' parameter defines the length of each chunks array. The algorithm works as follows:

  • iterate each array element (for loop) until main_array elements index is less than chunk array size (a % size !== size - 1), and push elements into temporary array.
  • else block - push element into temp array, push temp array into results array and create new empty temp array ();

    at the end if temp array length is not 0 then push it also into results array. that's it :)

Seems like the code tries to divide an array into chunks of smaller arrays of size size. Let's say you have a big bag full of apples and you want to reduce it to smaller apple bags each having at max 2 apples. How would you do in real life? You will go through the apples starting from first one and keep putting them in a small bag until it gets full. Then you move to another small bag and start to fill that it. Same thing is done here.

Inside if there is a condition checking if the temporary chunks have been filled and if not then keep pushing to the current temporary array. If yes then create a new array and keep pushing to it. temp=[] ensures the resetting.

It happens @Peter Pavluchenko. Let's walk through the code and see what it's doing.

the caller is specifying the size of chunks.

  • a % size !== size -1
    • % is a mod operator. so when a is divided by size what is the result? is the result not equal to size -1?

if the result of 'a' being divided by size is not equal to size -1, than we push the item to the end of our temp array.

If the result of 'a' being divided by size is equal to size - 1, we have found our first chunk! So lets' add the item to our temp array and add the temp array to our result array.

temp array - item 1 - item 2

result array - item -- item 1 -- item 2

so when you do result[0], you will get another array.

chunk = result[0]; chunk[0] = the actual object you might be interested in.

After we have pushed the temp array to the end of our result array, we need to reset it so we can start collecting items for the next chunk.

The last 'if' is looking for situations like, you are in the middle of a chunk, but it's not a whole chunk as specified by the size argument. so we have some objects in our temp array that we need to add to the result array before we leave the method.

It appears that the task is to split up a given array (arr) into an array of arrays, of which each array has length size - except perhaps for the last which has any "leftovers" if the length of array is not an exact multiple of size.

The way the given solution works is to go through arr, pushing its elements into the temporary array temp. But every size steps - this corresponds to the else condition inside the for loop - the temp array will have the correct length (namely size), so then the entire temp array, as a single element, is appended to the result array, and then returned to being an empty array to start over.

This way, result ends up with the chunks of size size as required. The final if statement just adds the "leftovers" on - that is, anything left in temp. (But we check that it isn't empty, otherwise if the length was an exact multiple you'd have an unwated empty array at the end of result.)

发布评论

评论列表(0)

  1. 暂无评论