Suppose I have an array: var a=[[1,1],[2,2],[3,3],[4,4]] If I write a[1] it returns [2,2]. But if I want to return the index of the array element [2,2] like a.indexOf([2,2]) it returns -1 which is not found. Is there an elegant way to find the index of an array element in an array?
Asked
Active
Viewed 95 times
0
Ming Huang
- 1,200
- 2
- 15
- 22
-
Since you need a custom equality, you probably want `findIndex`. Unless you want an ES3 solution? – John Dvorak Mar 02 '17 at 18:02
1 Answers
1
You can use Array.prototype.findIndex()
var index = a.findIndex(function(el) {
return el[0] == 2 && el[1] === 2
});
var index = a.findIndex(function(el) {
return el.every(function(n) {return n === 2})
});
guest271314
- 1
- 12
- 91
- 170