0

Something like this but generalized

let arr = [6, 5, 4, 3];
let i = 0, j = 0;
let result = [];

    result.push(arr[0]+arr[1],
arr[2]+arr[3]);

console.log(result
  • What if there is an odd number of items in the array? did you try to implement a loop to do it? – Nir Alfasi Oct 11 '21 at 14:57
  • This seems very much like a duplicate of: "[How to find the sum of an array of numbers](https://stackoverflow.com/q/1230233/82548)," have you tried the solutions offered there, or is there something unique in this problem that you haven't fully explained? – David Thomas Oct 11 '21 at 15:54
  • This is for a simple hash exercise on codewars I have to add an array of char codes each to the next in the array then base64encode new char – B-rad Gee Oct 11 '21 at 16:40

1 Answers1

0

Ignoring last element if array has odd number of elements:

function f(arr) {
  let result = [];
  for (let i=0; i<arr.length; i++) {
     if (i % 2==0 && i<arr.length-1) {
        result.push(arr[i] + arr[i+1]);
        i++;
     }
  };
  return result;
}

let arr = [6, 5, 4, 3];

console.log(f(arr));
console.log(f([1, 2, 3, 4, 5, 6, 7]));
Old Geezer
  • 14,854
  • 31
  • 111
  • 198