Link to home
Start Free TrialLog in
Avatar of FaheemAhmadGul
FaheemAhmadGulFlag 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.
Avatar of zc2
zc2
Flag of United States of America image

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
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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

startsWith() does not appear to be supported on IE
Avatar of Norie
Norie

Julian

I think you are right, it's not supported in IE11 anyway - not sure about other versions.
Avatar of 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.
You are welcome.