Looking for some assistance with a nested array of objects structured like this:
let pages = [
[
{
leftCol: [
{ height: 34, id: 10 },
{ height: 18, id: 20 },
{ height: 45, id: 30 },
{ height: 59, id: 40 },
],
},
{
rightCol: [
{ height: 34, id: 50 },
{ height: 34, id: 60 },
{ height: 34, id: 70 },
],
},
],
[
{
leftCol: [
{ height: 34, id: 80 },
{ height: 18, id: 90 },
{ height: 45, id: 100 },
{ height: 59, id: 110 },
],
},
{
rightCol: [
{ height: 34, id: 120 },
{ height: 34, id: 130 },
{ height: 34, id: 140 },
],
},
],
];
We need to create a method that can find the index of an element based on its id
as well as find the index of the outer array. For instance:
findIdx(pages, 30)
should return the index of the element (2) and the index of the outer array (0).
findIdx(pages, 110)
should return the index of the element (3) and the index of the outer array (1).
The current method looks like this:
function getIdxAndPageNumOfColumn(array, columnIdx, payloadId) {
let idx;
let pageNum;
for (pageNum = 0; pageNum < array.length; pageNum++) {
let leftCol = array[pageNum][0].leftCol;
let rightCol = array[pageNum][1].rightCol;
let column = columnIdx === 0 ? leftCol : rightCol;
idx = column.findIndex(item => item.id == payloadId);
if (idx > -1) break;
}
return {
idx: idx,
pageNum: pageNum,
};
}
However, this method requires specifying a columnIdx
parameter which seems to be causing issues. Any suggestions on how to improve this would be greatly appreciated.