js-mentorship-razvan / javascript

Javascript study notes
GNU General Public License v3.0
22 stars 2 forks source link

Split and then add both sides of an array together. #542

Closed RazvanBugoi closed 4 years ago

RazvanBugoi commented 4 years ago

https://www.codewars.com/kata/5946a0a64a2c5b596500019a/train/javascript

RazvanBugoi commented 4 years ago
function splitAndAdd(arr, n) {
  while(arr.length > 1 && n) {
    let arr1 = arr.slice(0, Math.floor(arr.length/2));
    let arr2 = arr.slice(Math.floor(arr.length / 2));
    let output = [];
    if(arr1.length == arr2.length) {
      arr1.map((el, index) => output.push(arr2[index] + el));
  } else {
      output.push(arr2[0]);
      arr1.map((el, index) => output.push(arr2[index+1] + el));
    }
    n-=1;
    arr = output;
}
  return arr;
}