0

If I have an array (sub) which has its own objects each with arrays within them and I'm looking for a particular value such as id === 9, how would I find the index of the object AND the index within that object's s array?

let a = {
  sub: [
     {
      id: 1,
      s: [
      	{id: 5},
        {id : 1}
      ]
    },
    {
      id: 2,
      s: [
      	{id: 6},
        {id: 3}
      ]
    },
    {
      id: 3,
      s: [
      	{id: 9},
        {id: 2}
      ]
    }
  ]
}

console.log(a.sub.findIndex(a => a.s.findIndex(z => z.id === 9)))

3 Answers 3

4

If you're sure there's only one matching element in all your sub arrays, here's a little trick with flatMap.

let a = {
  sub: [
     {
      id: 1,
      s: [
      	{id: 5},
        {id: 1}
      ]
    },
    {
      id: 2,
      s: [
      	{id: 6},
        {id: 3}
      ]
    },
    {
      id: 3,
      s: [
      	{id: 9},
        {id: 2}
      ]
    }
  ]
}

console.log(a.sub.flatMap((a, i) => {
  const j = a.s.findIndex(z => z.id === 9);
  return j > -1 ? [i, j] : []
}));

This will return an array containing the index, i, in a.sub where a matching element is found followed by the index, j, in a.sub[i].s where the matching element was found.

Note flatMap is a relatively recent addition to the standard, so it may not work in older browsers. Be sure to use a polyfill or a transpiler like Babel, if this is a concern in your case.

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

1 Comment

Can we have this logic for n level of nesting ?
2

Try this:

let a = {
  sub: [
     {
      id: 1,
      s: [
      	{id: 5},
        {id : 1}
      ]
    },
    {
      id: 2,
      s: [
      	{id: 6},
        {id: 3}
      ]
    },
    {
      id: 3,
      s: [
      	{id: 9},
        {id: 2}
      ]
    }
  ]
}

v = 9 

id1 = a.sub.findIndex(e => e.s.findIndex(ee => ee.id === v)!= -1)
id2 = a.sub[id1].s.findIndex(e => e.id === v )

console.log(id1) //index of the object
console.log(id2) //index within that object's s array

Comments

0

Modified answer of p.s.w.g, less likely to give you an eslint error.

let a = {
  sub: [
     {
      id: 1,
      s: [
        {id: 5},
        {id: 1}
      ]
    },
    {
      id: 2,
      s: [
        {id: 6},
        {id: 3}
      ]
    },
    {
      id: 3,
      s: [
        {id: 9},
        {id: 2}
      ]
    }
  ]
}

console.log(a.sub.flatMap((a, i) => {
  const j = a.s.findIndex(z => z['id'] === 9);
  return j > -1 ? [i, j] : []
}));

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.