Skip to content

Instantly share code, notes, and snippets.

@abdulhalim-cu
Last active November 10, 2017 09:36
Show Gist options
  • Save abdulhalim-cu/e419b21358c0ae877b45f05a80b043dc to your computer and use it in GitHub Desktop.
Save abdulhalim-cu/e419b21358c0ae877b45f05a80b043dc to your computer and use it in GitHub Desktop.
To find the people in the ancestry data set who were young in 1924, the following function might be helpful. It filters out the elements in an array that don’t pass a test.
// ancestry = http://eloquentjavascript.net/code/ancestry.js
function filter(array, test) {
var passed = [];
for (var i = 0; i < array.length; i++) {
if (test(array[i]))
passed.push(array[i]);
}
return passed;
}
console.log(filter(ancestry, function(person) {
return person.born > 1900 && person.born < 1925;
}));
/*
Transforming with map
Say we have an array of objects representing people, produced by filtering the ancestry array somehow.
But we want an array of names, which is easier to read.
The map method transforms an array by applying a function to all of its elements and building a new
array from the returned values. The new array will have the same length as the input array, but its
content will have been “mapped” to a new form by the function.
*/
function map(array, transform){
var mapped = [];
for (var i = 0; i < array.length; i++){
mapped.push(transform(array[i]));
}
return mapped;
}
var overNinty = ancestry.filter(function(person){
return person.died - person.born > 90;
});
console.log(map(overNinty, function(person){
return person.name;
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment