ciaksoy
ciaksoy

Reputation: 91

Finding nested object array indexes and wayback indexes

I have some nested object arrays in the array. I want to find the path of the key I want

For example:

const dataList = [
  [
      [{id: 100,name: 'Test1'}, {id: 120,'Test12'}],
      [{id: 101,name: 'Test1'}, {id: 121,'Test12'}],
      [{id: 102,name: 'Test1'}, {id: 122,'Test12'}],
    [
      [{id: 103,name: 'Test1'}, {id: 123,'Test12'}],
      [{id: 104,name: 'Test1'}, {id: 124,'Test12'}],
      [{id: 105,name: 'Test1'}, {id: 125,'Test12'}],
    ]
  ],
  [{id: 2,name: 'Test2'}, {id: 13,'Test13'}],
  [{id: 3,name: 'Test3'}, {id: 14,'Test14'}],
  [{id: 4,name: 'Test4'}, {id: 15,'Test15'}],
  [{id: 5,name: 'Test5'}, {id: 16,'Test16'}],
  [{id: 6,name: 'Test6'}, {id: 17,'Test17'}],
  [{id: 7,name: 'Test7'}, {id: 18,'Test18'}],
  [{id: 8,name: 'Test8'}, {id: 19,'Test19'}],
];

function findIndexPath(list, targetId) {
  //....
}

findIndexPath(dataList, 104); //output must [0,3,1,0]
findIndexPath(dataList, 16); //output must [4,1]

Arrays can go much deeper

Upvotes: 1

Views: 63

Answers (1)

majusebetter
majusebetter

Reputation: 1602

One approach could be something like this:

const dataList = [
  [
    [ { id: 100, name: 'Test1' }, { id: 120, name:'Test12' } ],
    [ { id: 101, name: 'Test1' }, { id: 121, name:'Test12' } ],
    [ { id: 102, name: 'Test1' }, { id: 122, name:'Test12' } ],
    [
      [ { id: 103, name: 'Test1'}, { id: 123, name:'Test12' } ],
      [ { id: 104, name: 'Test1'}, { id: 124, name:'Test12' } ],
      [ { id: 105, name: 'Test1'}, { id: 125, name:'Test12' } ],
    ]
  ],
  [ { id: 2, name: 'Test2'}, { id: 13, name:'Test13' } ],
  [ { id: 3, name: 'Test3'}, { id: 14, name:'Test14' } ],
  [ { id: 4, name: 'Test4'}, { id: 15, name:'Test15' } ],
  [ { id: 5, name: 'Test5'}, { id: 16, name:'Test16' } ],
  [ { id: 6, name: 'Test6'}, { id: 17, name:'Test17' } ],
  [ { id: 7, name: 'Test7'}, { id: 18, name:'Test18' } ],
  [ { id: 8, name: 'Test8'}, { id: 19, name:'Test19' } ],
];

function findIndexPathRecursively(list, targetId, path) {    
    let result = -1;
    for (let i = 0; i < list.length; i++) {
        if (list[i] instanceof Array) {
            const index = findIndexPathRecursively(list[i], targetId, path);
            if (index !== -1) {
                path.push(i);
                result = index;
                break;
            }
        }
        else if (list[i].id === targetId) {
            path.push(i)
            result = i;
            break;
        }
    }
    return result;
}

function findIndexPath(list, targetId) {
    const path = [];
    findIndexPathRecursively(list, targetId, path);
    return path.reverse();
}

console.log(findIndexPath(dataList, 104)); // output  [0,3,1,0]
console.log(findIndexPath(dataList, 16));  // output: [4,1]

Upvotes: 2

Related Questions