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.
7 Réponses
+ 3
Sort out meaning to filter only those elements matching the criteria?
+ 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" ) ) );
}
+ 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')...
+ 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.
+ 1
ASHISH PANDEY
Look at visph's answer then
0
Yes, to filter those element
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