Home > Net >  Using find on an array of strings
Using find on an array of strings

Time:09-22

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/

CodePudding user response:

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);
}

CodePudding user response:

Using indexOf in a one-liner

      const myArray = data[data.indexOf("two")   1]
  • Related