Skip to content

Instantly share code, notes, and snippets.

@justquick
Created August 1, 2011 01:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justquick/1117430 to your computer and use it in GitHub Desktop.
Save justquick/1117430 to your computer and use it in GitHub Desktop.
Pythonic array filtering in JS
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