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 ?
3 Answers 3
This should work
table.findIndex(element=>element.includes('restricted'))
Sign up to request clarification or add additional context in comments.
Comments
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
answered Oct 20, 2022 at 17:19
Mister Jojo
23k6 gold badges28 silver badges45 bronze badges
2 Comments
Andy
startsWith might be a little better than includes.Mister Jojo
@Andy, you are right, it's better ; thanks :)
var table = ['view-only-access', 'restricted-access', 'full-access'];
console.log(table.findIndex(i=>i.includes('view')));
answered Oct 20, 2022 at 17:16
Andrew Parks
8,1672 gold badges22 silver badges35 bronze badges
Comments
lang-js