Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
whys my javascript reduce function being skipped?

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));
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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));

about 4 years ago · Juan Pablo Isaza Report

0

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));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!