Skip to content

Instantly share code, notes, and snippets.

@TravelingMan
Last active January 11, 2016 19:59
Show Gist options
  • Save TravelingMan/78a0dd395d0aba100a3f to your computer and use it in GitHub Desktop.
Save TravelingMan/78a0dd395d0aba100a3f to your computer and use it in GitHub Desktop.
Filtering arrays with filter(), sort, reverse
/*
Transpose the order of the elements in the array
reverse() mutates the array and returns a reference to it.
*/
var array = [1,2,3,4,5,6,7];
var newArray = [];
newArray = array.reverse();
/*
Pass sort a callback with a comparison function. The following example sorts the array from
largest to smallest.
sort() will mutate the array and return a reference to it.
*/
var array = [1, 12, 21, 2];
array.sort(function(a, b) {
return b - a; // Use return a - b to sort from smallest to largest.
});
/*
The following filters out any value greater than/equal to 5.
In other words, if the return condition (val <= 5) is true, the value is added to the newArray array.
filter() does not mutate the array.
*/
var oldArray = [1,2,3,4,5,6,7,8,9,10];
var newArray = [];
newArray = oldArray.filter(function(val) {
return val <= 5;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment