« Back to Index

JS: sort two-dimensional Array

View original Gist on GitHub

Tags: #js #javascript #sort

sortBy.js

// sortBy accepts a two-dimensional array (results) and an array that indicates
// the required ordering for the data based on the given groupings (groups).
//
// EXAMPLE:
// The following inputs:
//
//    results = [["Foo", 3], ["Bar", 2], ["Baz", 1]]
//    groups  = ["Baz", "Bar", "Foo"]
//
//  Will sort the results into:
//
//    [["Baz", 1], ["Bar", 2], ["Foo", 3]]
//
function sortBy(results, groups) {
  groups.reverse().forEach((name) => {
    // This line ensures 'name' is the first element in the 'results' array.
    // By iterating over the given 'groups' in reverse we can enforce the required ordering.
    // All other elements are left in-place.
    results.sort((a, _) => (a[0] === name ? -1 : 0))
  })
}