Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using find on an array of strings

I have data similiar to this

const data = [
  'one',
  [
    {id: 1, value: 'A'},
    {id: 2, value: 'B'}
  ],
  'two',
  [
    {id: 3, value: 'C'},
    {id: 4, value: 'D'}
  ],
  'three',
  [
    {id: 5, value: 'E'},
    {id: 6, value: 'F'}
  ],
]

just looking for a way to find the array for a given "key" for example find the array after the element ‘two’

obviously
const myArray = data['two'] does not work

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am currently solving with the following.

let myResult = [];
for (let i = 0; i < data.length; i++) {
 if (data[i] === 'two')
  myResult = data[i + 1];
}

console.log(myResult);

but there must be a more concise way.

https://jsfiddle.net/yjb7hfk4/

>Solution :

Using indexOf in a one-liner

      const myArray = data[data.indexOf("two") + 1]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading