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

178
Views
Javascript multiply algorithm

I am trying to learn JavaScript arrays and algorithms and for loops. I am trying to make a function, that takes an array as a parameter, and has to multiply each number in the array with the next number. I can't seem to figure out what I am missing.

It just returns the array

function xNumbers (arr) {
    for (let i = 0; i < arr.lenght-1; i++) {
        var num1 = arr[i]
        var num2 = arr[i+1]
        var result;

        try {
            if (typeof (num1) == 'string' || typeof (num2) == 'string') {
                throw num1, "or", num2, "is not a number";
            } else if (num2 == 0) {
                throw 'Cant multiply with 0'
            } else {
                result = num1*num2
            }
                
            
        } catch (error) {
            console.log(error);
            result = NaN;

        } finally {
            arr[i] = result
        }
        
    }
    return arr
}

console.log(xNumbers([2,3,4,5]));
// expected output 6, 12, 20 - doesn't work
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

you can use the following code.

function xNumbers (arr) {
    arr = arr.map(x => Number(x))
    result = new Array(arr.length -1)
    for (let i = 0; i < arr.length-1; i++) {
        result[i] = arr[i] * arr[i + 1]
    }
    return result
}

console.log(xNumbers([2,3,4,5]));

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!