Reputation: 1077
Is it possible to return the array index using the array.find() method in typescript?
eg, I have an array of objects and can return an object using find on a object property name, but can I also somehow return the index of that item in the array?
Upvotes: 1
Views: 11609
Reputation: 2261
The above answers are correct that to get index you use .findIndex()
& to get the actual entry of the array you use .find()
However, it seems to me like you are asking how to get the index plus the entry in the array at once.
If I am correct you can try something like:
let array = ["Sunday", "Monday", "Tuesday", "Wednesday", "Friday", "Saturday"];
let tuesday = array.map((day,index) => {
if(day == "Tuesday")
return {day, index}
}).filter(day => day)[0];
console.log(tuesday);
You should get back an object with the entry & the index like this:
{"day": "Tuesday", "index": 2}
I am not sure if this is the cleanest way of getting them both at once, but it works.
Upvotes: 2
Reputation: 8422
Something like this:
const array1 = [5, 12, 8, 130, 44];
console.log(array1.findIndex((element) => element > 13));
And then to get actual value from that Index:
const array1 = [5, 12, 8, 130, 44];
const idx = array1.findIndex((element) => element > 13);
console.log(array1[idx])
Upvotes: 2
Reputation: 1060
find
returns the element. findIndex
returns the index.
findIndex
documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
Upvotes: 2