javascript - sum up each individual values from 2 arrays -


i'm trying understand conditional loop sum each elements 2 arrays, stumble upon latter part, don't understand achieved there.

can please explain me?

function arrays_sum(array1, array2) {     var result = [];     var ctr = 0;     var x = 0;      if (array1.length === 0)         return "array1 empty";     if (array2.length === 0)         return "array2 empty";      while (ctr < array1.length && ctr < array2.length) {         result.push(array1[ctr] + array2[ctr]);         ctr++;     }      if (ctr === array1.length) //i don't understand here onwards     {         (x = ctr; x < array2.length; x++) {             result.push(array2[x]);         }     } else {         (x = ctr; x < array1.length; i++) {             result.push(array1[x]);         }     }      return result; } 

let's suppose following 2 arrays , "sum":

array 1: 1  2  3  4   5  6   7   8  9 [length = 9] array 2: 2  4  6  8   2  4   6        [length = 7]  sum    : 3  6  9  12  7  10  13  8  9 [length = 9] 

pay attention last 2 items. sum equal value of first array because second array doesn't contain such number of values.

array 1: 1  2  3  4   5  6   7   8  9 array 2: 2  4  6  8   2  4   6   ?  ? 

that's algorithm does:

1) while both arrays have numbers @ i index - sum up.

ctr    : !  !  !  !   !  !   !  \|/   [ ctr   = 7 (remember: 0-based indexes)]        array 1: 1  2  3  4   5  6   7   8  9 [length = 9] array 2: 2  4  6  8   2  4   6        [length = 7]  sum    : 3  6  9  12  7  10  13   

here while (ctr < array1.length && ctr < array2.length) conditions breaks @ ctr < array2.length.

further, check ctr == array2.length returns true meaning array 2 on , need continue iterating through array1.

for (x = ctr; x < array1.length; i++) {     result.push(array1[x]); } 

2) while remaining array not on - add values it.

x    :                           !  !  \|/ [  x    = 10]                      array 1: 1  2  3  4   5  6   7   8  9      [length = 9 ] array 2: 2  4  6  8   2  4   6             [length = 7 ]  sum    : 3  6  9  12  7  10  13  8  9 

Comments

Popular posts from this blog

How to connect android app to App engine -

gcc - MinGW's ld cannot perform PE operations on non PE output file -

php - display validation error message next to the textbox in codeigniter -