Skip to content

Instantly share code, notes, and snippets.

@Jakobud
Last active June 20, 2022 14:50
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Jakobud/a0ac11e80a1de453cd86f0d3fc0a1410 to your computer and use it in GitHub Desktop.
Save Jakobud/a0ac11e80a1de453cd86f0d3fc0a1410 to your computer and use it in GitHub Desktop.
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 <jake.e.wilson@gmail.com>
@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;
}
@iamandrewluca
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