Faishal
Faishal

Reputation: 15

Find index of array by some string Javascript

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 ?

Upvotes: 0

Views: 637

Answers (3)

Mister Jojo
Mister Jojo

Reputation: 22320

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

Upvotes: 1

Enoch Omolere
Enoch Omolere

Reputation: 116

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

Upvotes: 3

Andrew Parks
Andrew Parks

Reputation: 8087

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

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

Upvotes: 0

Related Questions