Skip to content

Instantly share code, notes, and snippets.

@irony
Created January 29, 2012 18:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save irony/1700016 to your computer and use it in GitHub Desktop.
Save irony/1700016 to your computer and use it in GitHub Desktop.
Modern Javascript
// Lets start with an array
var array = ['hello', 'world'];
// forEach is supported from Javascript 1.6 which means it works in new browsers incl IE9 (not IE8 and back)
array.forEach(function(item){
console.log(item)
});
// other new array features is like LINQ i C#. filter() returns a new list filtered by the function
var filteredArray = array.filter(function(item){
return item == 'hello';
});
// returns a new array changed by the function. In this case will return a new array with the contents ['HELLO', 'WORLD'].
array.map(function(item){return item.toUpperCase()});
// every returns true if the whole array returns true.
array.every(function(item){ return item == 'hello' });
// some returns true if any of the array items returns true.
array.some(function(item){ return item == 'hello' });
// returns a part of the array. In this case the first item in the array (same as .pop()).
array.splice(0, 1);
// sort in alphabetic order
var sortedArray = array.sort(function(a,b){
return a-b;
})
// sort descending alpabetic order
var sortedArray = array.sort(function(a,b){
return b-a;
})
// now we will show how to use the new functions, but first we must have an array.
var playHistory = [
{
artist:'Madonna',
title:'Frozen'
},
{
artist:'Madonna',
title:'La Isla Bonita'
},
{
artist:'Madonna',
title:'American Pie'
},
{
artist:'Madonna',
title:'Frozen'
},
{
artist:'Madonna',
title:'Frozen'
}
];
var group = [];
// OK, now we want to get the artist with most albums
var topSongs = playHistory
// we go trough the array and return a reduced list of top albums
.map(function(item){
// we'll initialize a temporary variable
if (song = group[item.title]) {
song.count++;
return null; // by returning null we'll return a smaller array than we had before
}
else
return group[item.title] = {artist: item.artist, title : item.title, count : 1};
}, topSongs)
// sort on artists with most albums
.sort(function(a,b){return a.count > b.count})
// we'll take top 3, similar to LINQ .take(3);
.slice(0, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment