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

FaheemAhmadGul
FaheemAhmadGul used Ask the Experts™
on
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.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
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

Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
You can use the Array.filter() function
This should do it
<script>
let haystack = ['apple','boomerang','bolivia','childern','delta','boland'];
let needle = 'bo';
let newData = haystack.filter(item => item.substr(0, needle.length) == needle);
console.log(newData);
</script>

Open in new window

For backward compatibility
<script>
var haystack = ['apple','boomerang','bolivia','childern','delta','boland'];
var needle = 'bo';
// In case arrow functions are not supported on target platform
var newData = haystack.filter(function(item) {
   return item.substr(0, needle.length) == needle;
});
console.log(newData);
</script>

Open in new window

NorieAnalyst Assistant
Commented:
Can' t you use filter?
var words = ['simple', 'single', 'side', 'sacked', 'apple', 'orange'];

var begins = 'si';

var myFilteredWords =[];

myFilteredWords =  words.filter(word => word.startsWith(begins));

console.log(myFilteredWords);

console.log(myFilteredWords);

Open in new window

Eddie ShipmanAll-around developer

Commented:
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

Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
startsWith() does not appear to be supported on IE
NorieAnalyst Assistant

Commented:
Julian

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

Author

Commented:
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.
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
You are welcome.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial