Skip to content

Instantly share code, notes, and snippets.

@icodejs
Created April 3, 2012 15:42
Show Gist options
  • Save icodejs/2293019 to your computer and use it in GitHub Desktop.
Save icodejs/2293019 to your computer and use it in GitHub Desktop.
Messing around with sorting arrays
// ---------- Messing around with sorting --------------
(function stableSort(v) {
var dv = [];
for (var i=0; i<v.length; i++) {
dv[i] = [v[i], i];
}
dv.sort();
for (var i=0; i<v.length; i++) {
v[i] = dv[i][0];
}
console.log('attempt 1: ', dv);
}([35, 6, 236, 7, 8, 324, 5, 1 , 3]));
// ------------------------
(function (arr) {
console.log('attempt 2: ', arr.sort());
}([35, 6, 236, 7, 8, 324, 5, 1 , 3]));
// ------------------------
(function(array) {
array.sort(function (a, b) {
return a-b;
});
console.log('attempt 3: ', array);
}([35, 6, 236, 7, 8, 324, 5, 1 , 3]));
// ------------------------
(function(array) {
array.sort();
console.log('attempt 4: ', array);
}(['tyrone', 'joe', 'alex', 'vinny', 'rob', 'zack', 'andy', 'eric' , 'darren']));
// ------------------------
(function(array) {
var objectArray = [
{firstname: 'Marie', lastname: 'Doe', age: 28},
{firstname: 'Will', lastname: 'Brown', age: 28},
{firstname: 'James', lastname: 'White', age: 28},
{firstname: 'John', lastname: 'Doe', age: 25},
{firstname: 'Sarah', lastname: 'Doe', age: 25},
{firstname: 'George', lastname: 'Williams', age: 25}
];
objectArray.sort(function callbackFunc(a,b){
if(a.lastname === b.lastname){
if(a.firstname === b.firstname){
return 0;
}
return (a.firstname < b.firstname) ? -1 : 1;
}
return (a.lastname < b.lastname) ? -1 : 1;
});
console.log('attempt 5: ', objectArray);
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment