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

115
Views
JavaScript. 10%5 === 0 --> false?

Please help to find mistakes in my code:

function multipleOfIndex(array) {
    return array.forEach( item => console.log(item%array.indexOf(item) === 0) )
}
    
console.log(multipleOfIndex([68, -1, 1, -7, 10, 10])) // false, true, false, false, false, false 

obviously, I was expecting

console.log(multipleOfIndex([68, -1, 1, -7, 10, 10])) // false, true, false, false, false, true 

Thanks!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

The problem is relying on indexOf when more than one value is the same in the array - array.indexOf(10) is always 4, see the extended log here:

function multipleOfIndex(array) {
    return array.forEach( item => console.log(item,array.indexOf(item),item%array.indexOf(item) === 0) )
}
    
console.log(multipleOfIndex([68, -1, 1, -7, 10, 10])) // false, true, false, false, false, false

The solution is to use the forEach index parameter (2nd one) https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

function multipleOfIndex(array) {
    return array.forEach( (item,idx) => console.log(item%idx === 0) )
}
    
console.log(multipleOfIndex([68, -1, 1, -7, 10, 10])) // false, true, false, false, false, false

about 4 years ago · Juan Pablo Isaza Report

0

The [indexOf] method returns the first index of a given element that can be found in the array. If it does not exist, it returns - 1. So the [indexOf] value of the last 10 is 4.

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!