Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to sum 3 to 3 values on an array

im trying to do a convertor that converts values base-16 to base-8 just for fun but i got an issue, the thing is, i need to sum the values of an array 3 to 3, for exemple, an array have ["1","2","0","1"], i need to sum the values of the positions 0, 1 and 2, and for the position 4 is separate of the first 3, returning ["3","1"], im trying doing without any libraries, i just need to know how can i do this and every try of search about this just find about .push() or .slice()

well, thanks for reading and have a nice day

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use Array.fn.reduce by pushing the element into the result(a) if its index(i) is divisible by 3, otherwise grab the last element and increase it’s value by the current value (b).

const arr = [1, 2, 5, 3, 4];

const res = arr.reduce((a, b, i) => {
  if (i % 3 === 0) return [...a, b];
  else { a[a.length - 1] += b; return a; }
}, []);

console.log(arr, res);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading