Last active
January 11, 2016 19:59
-
-
Save TravelingMan/78a0dd395d0aba100a3f to your computer and use it in GitHub Desktop.
Filtering arrays with filter(), sort, reverse
This file contains 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
/* | |
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(); |
This file contains 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
/* | |
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. | |
}); |
This file contains 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
/* | |
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