Home > database >  Find index of array by some string Javascript
Find index of array by some string Javascript

Time:10-21

I'm working with an array like this one :

var table = ['view-only-access', 'restricted-access', 'full-access'];

I wanted to find the index by only string like 'view' , 'restricted', or 'full'. I have tried the .indexOf() but it requires the full string. does anyone know how to do this ?

CodePudding user response:

var table = ['view-only-access', 'restricted-access', 'full-access'];

console.log(table.findIndex(i=>i.includes('view')));

CodePudding user response:

This should work table.findIndex(element=>element.includes('restricted'))

CodePudding user response:

const
  table    = ['view-only-access', 'restricted-access', 'full-access']
, f_search = str => table.findIndex( x => x.startsWith( str ) )
  ;
  
console.log( f_search('full') )         // 2
console.log( f_search('restricted') )  // 1
console.log( f_search('view') )       // 0

  • Related