0

How To sort out the matched string of Array using initials.

I have a array Var A = [ "Dry Nuts" , "Hazel Nut" , " Flax Seed" , "Pumpkin Seed" , "Watermelon Seed" , "Almonds" ]; Now if some one put N , it sort out all String Containing Nuts in it, If someone put S, it sort out all contains seeds in it.

2nd Mar 2021, 3:22 AM
ASHISH PANDEY
ASHISH PANDEY - avatar
7 Réponses
+ 3
Sort out meaning to filter only those elements matching the criteria?
2nd Mar 2021, 4:23 AM
Ipang
+ 3
Use array::filter method to get matching items 👇 https://developer.mozilla.org/docs/web/javascript/reference/global_objects/array/filter Use string::includes method to check whether a string includes (contains) another string 👇 https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/string/includes Example: const A = [ "Dry Nuts" , "Hazel Nut" , " Flax Seed" , "Pumpkin Seed" , "Watermelon Seed" , "Almonds" ]; let filterKey = prompt( "Enter N or S", "N" ).toUpperCase(); if( filterKey == "N" ) { // filter elements which includes word "Nut" console.log( A.filter( element => element.includes( "Nut" ) ) ); } else if( filterKey == "S" ) { // filter elements which includes word "Seed" console.log( A.filter( element => element.includes( "Seed" ) ) ); }
2nd Mar 2021, 5:19 AM
Ipang
+ 2
if you want to search for string with words starting with a specific letter, you could do: var letter = new RegExp('\\b'+prompt('Enter a letter'),'i'); console.log(A.filter(s => letter.test(s)) for case sensitive search, just remove the RexExp 2nd parameter ('i')...
2nd Mar 2021, 9:35 AM
visph
visph - avatar
+ 1
ASHISH PANDEY Quoted from your original post above "Now if some one put N , it sort out all String Containing Nuts in it, If someone put S, it sort out all contains seeds in it" And now, after 1 day, you change the condition of the game.
4th Mar 2021, 3:39 AM
Ipang
+ 1
ASHISH PANDEY Look at visph's answer then
4th Mar 2021, 3:40 AM
Ipang
0
Yes, to filter those element
2nd Mar 2021, 5:01 AM
ASHISH PANDEY
ASHISH PANDEY - avatar
0
Ipang Your code is specifically for N, and S, But I wish that, wether its N or Nu or Nut , Or wether its S or see or seed, it give the respective output, In short either the user entered data is matching with first or second word.... It output result on that
4th Mar 2021, 3:33 AM
ASHISH PANDEY
ASHISH PANDEY - avatar