Avatar of FaheemAhmadGul
FaheemAhmadGul
Flag for United Kingdom of Great Britain and Northern Ireland asked on

Javascript function to filter a an array of strings based on starting letters of the strings in the array

I need help writing a Javascript function which will take a string as an arugment and then filter out an array of strings starting with the string I pass as an argument.
So if I have the following array:
let words = ['simple', 'single', 'side', 'sacked', 'apple', 'orange']
I need a javascript funtion that will look at every string in this array, and give me a second array called myFilteredWords which start with the letters 'si" - assumuming that I pass 'si" as an argument to the funtion.
JavaScriptWeb Development Software

Avatar of undefined
Last Comment
Julian Hansen

8/22/2022 - Mon
zc2

Like this?
function f( s, a ) {
    var sl = s.length;
    var na = [];
    for( var i in a )
        if( a[i].substr( 0, sl ) == s )
            na.push(a[i]);
    return na;
}

Open in new window

ASKER CERTIFIED SOLUTION
Julian Hansen

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
SOLUTION
Norie

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Eddie Shipman

Give this a try:
var words = ['simple', 'single', 'side', 'sacked', 'apple', 'orange'];
const regex = new RegExp('^si', 'g')
const myFilteredWords  = words.filter(value => regex.test(value));
console.log(myFilteredWords);

Open in new window

Julian Hansen

startsWith() does not appear to be supported on IE
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
Norie

Julian

I think you are right, it's not supported in IE11 anyway - not sure about other versions.
FaheemAhmadGul

ASKER
Many thanks all the experts for your comments. As both Julian's and Norie's solutions were most helpful and I accepting both. Hope this is OK.
Julian Hansen

You are welcome.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.