Created
August 1, 2011 01:25
-
-
Save justquick/1117430 to your computer and use it in GitHub Desktop.
Pythonic array filtering in JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function filter(callback, array){ | |
// Given a callback function taking one argument and an array, | |
// return a new array of items passing the callback check. | |
// The callback function is called once per item in the array and must return true/false. | |
var ra = new Array(); | |
for(var i in array){ | |
if (callback(array[i])) | |
ra.push(array[i]); | |
} | |
return ra; | |
} | |
var names = ["Chris", "Kate", "Steve", "Steph", "Alice", "Theodore"]; | |
alert( | |
filter( | |
function(item){ // callback | |
// Starts with 'S' | |
return item.toString()[0] == 'S'; | |
}, | |
names // array | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment