Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Sort a SASS map
/// map-sort
/// Sort map by keys
/// @param $map - A SASS map
/// @returns A SASS map sorted by keys
/// @requires function list-sort
/// @author Jake Wilson <>
@function map-sort($map) {
$keys: list-sort(map-keys($map));
$sortedMap: ();
@each $key in $keys {
$sortedMap: map-merge($sortedMap, ($key: map-get($map, $key)));
@return $sortedMap;

This comment has been minimized.

Copy link

iamandrewluca commented Jan 21, 2018

Here is a variant that will sort by values.

@function map-sort-by-values($map) {
  // Transform map to zipped list
  $keys: ();
  $values: ();

  @each $key, $val in $map {
    $keys: append($keys, $key);
    $values: append($values, $val);

  $list: zip($keys, $values);

  $sortedMap: ();
  @while length($list) > 0 {

    // Find smallest pair
    $smallestPair: nth($list, 1);
    @each $pair in $list {
      $value: nth($pair, 2);
      $smallestValue: nth($smallestPair, 2);
      @if $value < $smallestValue {
        $smallestPair: $pair;

    // Add smallest pair to sorted map
    $key: nth($smallestPair, 1);
    $value: nth($smallestPair, 2);
    $sortedMap: map-merge($sortedMap, ($key: $value));

    // Remove from list smallest pair
    $smallestPairIndex: index($list, $smallestPair);
    $newList: ();
    @for $i from 1 through length($list) {
      @if $i != $smallestPairIndex {
        $newList: append($newList, nth($list, $i), "space");
    $list: $newList;

  @return $sortedMap;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.