Home > OS >  How do you concatenate several arrays into one?
How do you concatenate several arrays into one?

Time:07-29

const sumAll = function (min, max) {
  const allSums = [];
  const initialValue = 0;

  for (let i = min; i <= max; i  ) {
    allSums.push([i]);
  }
  console.log(allSums); // 

  let sumTotal = allSums.reduce(function (acc, curr) {
    acc  = curr;
    return acc;
  }, initialValue);

  console.log(sumTotal);
};

sumAll(1, 4) returns 01234 instead of 10.

I can see that allSums is 4 arrays inside of an array. How would I go about concatenating them? Thank you for the help!

CodePudding user response:

Realised this could easily be achieved by adding a spread operator before pushing to allSums.

for (let i = minNumber; i <= maxNumber; i  ) {
    allSums.push(...[i]);
  }

CodePudding user response:

No need to create an array at all, you can Array#push the value directly. That's the goal, right? So,

allSums.push([i]); //or allSums.push(...[i]);

Should be:

allSums.push( i );
  • Related