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 in groups of 3, for exemple, an array have ["1","2","0","1"]
, i need to sum the first 3 values and do that for the rest of the array, 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
2
Answers
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
).You can combine the reduce method to sum the first three elements and the slice method to join the sum result with the rest of the elements of the array in a new array.
For example: