Home > Software design >  Get index of parent given a value of a child array of arrays
Get index of parent given a value of a child array of arrays

Time:02-14

I'm trying to get the index of the parent given an element inside the children, for example, I have a list variable (2) [Array(1), Array(2)] with this structure:

[
    [
        {id: "1",contactType: {id: "phoneNumber",company: {id: "01",name: "Company01"}},value: "5555555555"},
    ],
    [
        {id: "2",contactType: {id: "phoneNumber",company: {id: "03",name: "Company03"}},value: "7777777777"},
        {id: "3",contactType: {id: "phoneNumber",company: {id: "05",name: "Company05"}},value: "8888888888"},
    ],
]

I tried using includes and findIndex to verify if such element exist first and then get the parent index:

list.includes('5555555555', 0);

I expected to get true because I asked include to begin searching in index 0 of the list exactly where "5555555555" element is, but i got false instead.

Also tried with:

list.findIndex(x => x.value === '5555555555');

I expected 0 since element 5555555555 is in parent 0 index. But got -1 instead.

I also tried using flat() to get into the children and the use includes, but then I lose the 0 and 1 index of the original list.

Expected output:

foo(list,'7777777777'); should return 1 since that element is inside the second array of the list or foo(list,'8888888888'); should also return 1 since that element is also inside the second array of the list.

Can someone guide me on how to approach this issue?

CodePudding user response:

Use Array.findIndex with condition

const data = [
[
    {id: "1",contactType: {id: "phoneNumber",company: {id: "01",name: "Company01"}},value: "5555555555"},
],
[
    {id: "2",contactType: {id: "phoneNumber",company: {id: "03",name: "Company03"}},value: "7777777777"},
    {id: "3",contactType: {id: "phoneNumber",company: {id: "05",name: "Company05"}},value: "8888888888"},
],
];

const index = data.findIndex(item => item.findIndex(node => node.value === "5555555555") > -1);
console.log(index)

CodePudding user response:

const arr = [
[
    {id: "1",contactType: {id: "phoneNumber",company: {id: "01",name: "Company01"}},value: "5555555555"},
],
[
    {id: "2",contactType: {id: "phoneNumber",company: {id: "03",name: "Company03"}},value: "7777777777"},
    {id: "3",contactType: {id: "phoneNumber",company: {id: "05",name: "Company05"}},value: "8888888888"},
],
];
const index = arr.flat().findIndex(item => item.value === "7777777777")
console.log(index);

  • Related