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

120
Views
Loop backwards Javascript Array

I would like to loop backwards in a array in javascript and then get the index of each element in the array for example if a array has 10 elements and is looped backwards it would log 9, 8, 7, 6, 5, 4, 3, 2, 1, 0. for some werid reason i am getting a bunch of negaitive -1s and im confused why it wont just return the index properly.

here is the code

//Arrays I would like to pass into the function

const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8];
const invalid1 = [4, 5, 3, 2, 7, 7, 8, 7, 7, 1, 0, 9, 1, 7, 9, 5];

function validateCred(arr) {
    let sum = 0;
    for (let i = arr.length - 1; i >= 0; i--) {
        console.log(arr.indexOf(i));
    }
}

console.log(validateCred(valid1));
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

why -1s?

It is because of arr.indexOf(i) when the loop starts i=15 so:

arr.indexOf(15) will return -1 because you don't have a 15 in your array.

next i=14 same as above.

. . .

i=9 then it will find the element at index 3.

about 4 years ago · Juan Pablo Isaza Report

0

As UnholySheep explains above, Array.indexOf(i) gives you the index of the first occurrence of the value represented by i in the array. Here is some code to help you debug:

function validateCred(arr) {
  let sum = 0
  for (let i = arr.length - 1; i >= 0; i--) {
    console.log(i)        // log the index
    console.log(arr[i])   // log the value
  }
}
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!