What is findIndex.
Using findIndex method we can easily find out the index of an element in the array. Let us check the code.
var list = [
{name:'Prashobh'},
{name:'Abraham'},
{name:'Deepthi'}
]
var index = list.findIndex(function(e){return e.name == 'Prashobh'})
console.log(index);
Result : 0
This is the most suggested way to do this and it will work for most of the browsers. As I mentioned most of the browsers, let us check which are those browsers not supporting findIndex method.
Browser support for findIndex.
Chrome 45.0 and above: Supports
Firefox 25.0 and above: Supports
Internet Explorer: No support
Microsoft Edge: Supports
Opera: Supports
Safari 7.1 and above: Supports
So what we can do to make sure it will work in other browser as well. Let us modify our code like below.
Another approach.
var index;
list .some(function(e, i) {
if (e.name == 'Prashobh') {
index = i;
return true;
}
});
console.log(index);
Result : 0
It will work in almost all the browsers but not in IE 11. So let’s modify our code again like below.
Final one.
var index;
for (var i = 0; i < list.length; ++i) {
if (list[i].name == 'Prashobh') {
index = i;
break;
}
}
console.log(index);
Result : 0
This is basic way to do this and it will work in almost all modern browsers including IE8.
Related Post
1. HTTP status codes and meanings.
2. Jquery select all/de select all checkbox
3. How to download file from backend to UI
4. Get users browser name | get user ip address
I was surfing net and fortunately came across this site and found very interesting stuff here. Its really fun to read. I enjoyed a lot. Thanks for sharing this wonderful information. ucmini
ReplyDelete