Reputation: 3
I want to find the index of the NestedArray (userdata) inside the SearchArray (data). I already have the existing code inserted below.
var data = [["John",25],["James",19],["Liam",27],["George",22]]
var user = "Liam";
var userdata = [];
const userfound = data.some(function(row){
if(row[0] == user){
userdata = row;
return true;
}
else {return false;}
});
console.log(userfound);
console.log(data);
console.log(userdata);
The code above gives the corresponding log:
true
Array [Array ["John", 25], Array ["James", 19], Array ["Liam", 27], Array ["George", 22]]
Array ["Liam", 27]
normally I would try to find an index of an item in an Array like so:
const index = data.findIndex( x => userdata.includes(x));
However this doesn't work for a 2d Array. Does anyone have a clue?
Upvotes: 0
Views: 3022
Reputation: 64032
function cantfindmyindex() {
var data = [["John", 25], ["James", 19], ["Liam", 27], ["George", 22]];
var user = "Liam";
console.log(data.map(r => r[0]).indexOf(user));
}
Upvotes: 3
Reputation: 21902
You can use findIndex()
with a 2 dimensional array as follows:
var data = [["John",25],["James",19],["Liam",27],["George",22]]
var user = "Liam";
const isUser = (element) => element[0] === user;
console.log( data.findIndex(isUser) );
Here, isUser
is a testing function that can be passed to findIndex()
. Each element
is an entry in the outer array - hence element[0]
is the first value (the name) in each sub-array.
It will stop at the first successful match.
Upvotes: 0