1

The problem I'm trying to solve is quite simple but since there are a lot of (hidden) magic functions in javacript I'm wondering if there is a quick solution for that. So far I've only seen people trying to know if an array contains a string (boolean) but that's not what I'm trying to achieve.

I have a simple string array :

var myarray = [ "word1", "word2", "potatoe"]

If I'm looking for the substring "word", I would like to write a function that returns a new array which only contains the matching elements of the original array. In that case it would be : ["word1", "word2"].

What's the best approach, do I have to loop and create the new array by hand ?

Thanks

1 Answer 1

1

No, you don't need a loop. Look into Array.prototype.filter(), which takes a callback function as an argument:

arr.filter(callback[, thisArg])

This function tests the elements of your array one by one, invoking the callback function on each element. The new array will consist of the elements for which your callback function returns true.

Source: Mozilla Developer Network

1
  • Amazing, thank you. I'll try this out right now. These functions using callbacks are typical of a javascript way of thinking that I don't have yet.
    – tobiak777
    Commented Jun 15, 2014 at 14:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.