Reputation: 48
So, what I'm trying to get is the index of a 2d array of objects, let's say I have the following
const arr = [
[{id: 1}, {id:2}],
[{id:3},{id:4},{id:5}]
]
If I'd want to get the index where id=3 it would be arr[1][0]
, Is there any way to achieve this using vanilla JS or any helper library?
Upvotes: 0
Views: 265
Reputation: 456
const arr = [
[{id: 1}, {id:2}],
[{id:3},{id:4},{id:5}]
];
function getIndex(arr, value){
let rowIndex = null;
let valueIndex = null;
arr.forEach(( nestedArray, index) => {
if(!valueIndex) rowIndex = index;
nestedArray.every((val, valIndex) => {
if(val.id === value) {
valueIndex = valIndex;
return false
}
return true;
});
})
return {
rowIndex,
valueIndex
}
}
console.log(getIndex(arr, 3))
Upvotes: 0
Reputation: 653
You can achieve this by nesting two for loops.
function findNestedIndices(array, id) {
let i;
let j;
for (i = 0; i < array.length; ++i) {
const nestedArray = array[i];
for (j = 0; j < nestedArray.length; ++j) {
const object = nestedArray[j];
if (object.id === id) {
return { i, j };
}
}
}
return {};
}
const array = [
[{id: 1}, {id:2}],
[{id:3},{id:4},{id:5}]
];
const { i, j } = findNestedIndices(array, 3);
console.log(i, j); // 1, 0
Upvotes: 1
Reputation: 4464
const arr = [
[{id: 1}, {id:2}],
[{id:3},{id:4},{id:5}]
];
let searchIndex = 3;
let x = arr.findIndex(sub => sub.find(el => el.id == searchIndex));
let y = arr[x].findIndex(el => el.id == searchIndex);
console.log(x, y)
Upvotes: 1
Reputation: 27245
Might be a more efficient way to do it, but you could accomplish this via array.findIndex
:
const test = [
[{id: 1}, {id:2}],
[{id:3},{id:4},{id:5}]
];
function find(arr, id) {
const firstIndex = arr.findIndex(entry => entry.some(({id: x}) => x === id));
if (firstIndex > -1) {
const secondIndex = arr[firstIndex].findIndex(({ id: x }) => x === id );
return [firstIndex, secondIndex];
}
}
console.log(find(test, 2)); // [0, 1]
console.log(find(test, 4)); // [1, 1]
console.log(find(test, 5)); // [1, 2]
Upvotes: 1