Home > Blockchain >  whys my javascript reduce function being skipped?
whys my javascript reduce function being skipped?

Time:10-02

my last function reducedArr, is being skipped?

when I console.log I get the newArry returned?

why is not executed??

const sumAll = function(...args) {
    let newArr = [...args];
    let sortedArr = newArr.sort(function(a,b) {
        return a - b;
    })
    let lastArr = ['']
    for (let i = sortedArr[0]; i < sortedArr[1];   i ) {
        lastArr.push(i)
    }
    let reducedArr = lastArr.reduce(function(previousValue,currentValue) {
        return previousValue   currentValue;
    })
    return reducedArr;
    
};

console.log(sumAll(1,4));

CodePudding user response:

Your last reduce is still working, it just appends string instead of number because you init let lastArr = [''] with a '' item.

Update it to let lastArr = []. You will see the final result.

const sumAll = function(...args) {
    let newArr = [...args];
    let sortedArr = newArr.sort(function(a,b) {
        return a - b;
    })
    let lastArr = []
    for (let i = sortedArr[0]; i < sortedArr[1];   i ) {
        lastArr.push(i)
    }
    
    console.log(lastArr);
    let reducedArr = lastArr.reduce(function(previousValue,currentValue) {
        return previousValue   currentValue;
    })
    return reducedArr;
    
};

console.log(sumAll(1,4));

CodePudding user response:

You can just write the code more succinct using Array.from and reduce

NOTE: If you want to add 1 2 3 4 if you say as 1-4 then you can replace

Array.from({ length: end - start   1 }, (_, i) => i   start)

const sumAll = function (a, b) {
  const [start, end] = a > b ? [b, a] : [a, b];
  return Array.from({ length: end - start }, (_, i) => i   start)
              .reduce((acc, curr) => acc   curr);
};

console.log(sumAll(1, 4));
console.log(sumAll(4, 1));

  • Related