How can i find the index of the element of an Array? [closed]

Tags:



Here is my code, it gives me undefined i have also tried indexof() method

let Numbers = [2,3,1,5,6,7,8 ];`
console.log("Unsorted array " + Numbers);
for(var i=0 ;i<Numbers.length;i++){`
alert(Numbers.findIndex[i]);
}    

Answer

The below code would work after some changes in your code –

let Numbers = [2, 3, 1, 5, 6, 7, 8];
console.log("Unsorted array " + Numbers);
for (var i = 0; i < Numbers.length; i++) {
  console.log(Numbers.indexOf(Numbers[i]));
}

In your case, you were using findIndex() which takes a function and executes it for each element of the array. You were passing it a number which is not correct. Also, the invocation of function you were doing was not correct – use () brackets and not [] brackets for function call.

Also, the i itself is the index. I don’t know why you would need to use indexOf to get the index of element which you already know is present at a particular index. This method wouldn’t be practical unless your array has duplicates and you need to find the first occurring index number for each element of array.

As a side tip, avoid using alert for such purposes. Stick with console log.



Source: stackoverflow