Test If The Array Index Equals The Array Value

  • A+
Category:Languages

The code is to return the lowest index in an array when the value in the array is the same as the index. If there are no matches i should return -1. For example:

indexEqualsValue([-8,0,2,5]) output: 2 //array[2] == 2  indexEqualsValue([-1,0,3,6]) output: -1  //no matches 

The code works when there are no matches or if the length of the array is zero, but not at other times. I think the problem is the first condition in my if statement. I don't necessarily want an answer, more tips on what I should check/rewrite.

Thanks!

function indexEqualsValue(a) {     return a.reduce(function(acc, currV, currI) {if (currI === currV) {return currV;     } else {       return -1;     }   }, 0); } 

 


You could just find the index with Array#findIndex.

const indexEqualsValue = array => array.findIndex((v, i) => v === i);  console.log(indexEqualsValue([-8, 0, 2, 5])); //  2 console.log(indexEqualsValue([-1, 0, 3, 6])); // -1

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: