skip to Main Content

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


  1. 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);
    Login or Signup to reply.
  2. 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:

    const array = ["0", "1", "2", "1", "3"]
    const sum = array.reduce((accumulator, currentValue, index) => {
      return index < 3 ? `${Number(accumulator) + Number(currentValue)}` : accumulator 
    })
    const result = [sum, ...array.slice(3)] 
    console.log(result) // ["3", "1", "3"]
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search