0

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?

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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]

Comments

1

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)

Comments

0

 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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.