Skip to content
Advertisement

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

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/

Advertisement

Answer

Use indexOf() to find the index of the string, then add 1 to get the result.

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'}
   ],
]

let index = data.indexOf("two");
let myResult;
if (index != -1) {
  myResult = data[index+1];
  console.log(myResult);
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement