How can I get the index of an element by finding the value of a property?

Viewed 60

Kinda tricky question. I have this set of panels and I would like to make a function that would allow me to find the position in the array of this elements. However, in this array, there are subarrays. In this case, I just want to get the key of the parent array.

Example:

[
   {
      "name":"apple"
   },
   {
      "name":"bone"
   },
   [
      {
         "name":"banana"
      },
      {
         "name":"tea"
      }
   ]
]

So, if I put apple in the function, it returns me 0, if I wanted to find the element with the name bone, it would return me the index 1 and if I wanted to find the index of banana, it would return me 2 and tea would also return me 2.

Anyone has an idea, how I can achieve this in a clean way?

Thanks!

1 Answers

const input = [{name:"apple"},{name:"bone"},[{name:"banana"},{name:"tea"}]];

const myFind = (name) => input.findIndex(e => 
  Array.isArray(e) // check if element is array
    ? e.some(x => x.name === name) // if yes, check if contains name
    : e.name === name // if no, check if elements name is equal name 
)

console.log('bone:', myFind('bone'))
console.log('banana:', myFind('banana'))
console.log('tea:', myFind('tea'))

Related