Created
December 22, 2015 20:44
-
-
Save gonz/a28df76ee4c99e01b84c to your computer and use it in GitHub Desktop.
JS sort
This file contains hidden or 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
function getSortedIndexes(table) { | |
var indexes = []; | |
for (var i = 0; i < table.headers.length; i += 1) { | |
indexes.push(i); | |
} | |
return indexes.sort((function (t) { | |
return function (a, b) { | |
return ((t.headers[a].name < t.headers[b].name) ? -1 : ((t.headers[a].name > t.headers[b].name) ? 1 : 0)); | |
}; | |
})(table)); | |
}; | |
function sortArraysWithIndexes(table, inputArrays) { | |
var index = getSortedIndexes(table), sortedArrays = []; | |
inputArrays.forEach(function (arr) { | |
var tmp = []; | |
for(var i = 0; i < arr.length; i++) { | |
tmp[i] = arr[index[i]]; | |
} | |
sortedArrays.push(tmp); | |
}); | |
return sortedArrays; | |
}; | |
function sortTable(table) { | |
var arrs, headers; | |
arrs = table.rows; | |
arrs.unshift(table.headers); | |
arrs = sortArraysWithIndexes(table, arrs); | |
headers = arrs.shift(); | |
return { | |
headers: headers, | |
rows: arrs | |
} | |
} | |
sortTable({ | |
headers: [{name: 'b'}, {name: 'a'}, {name: 'c'}], | |
rows: [ | |
[451, 31, 22], | |
[51, 31, 435], | |
] | |
}); | |
// Expected output: | |
// | |
// { | |
// headers: [{name: 'a'}, {name: 'b'}, {name: 'c'}], | |
// rows: [ | |
// [31, 451, 22], | |
// [31, 51, 435], | |
// ] | |
// }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment