Create a gist now

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 <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

This comment has been minimized.

Show comment Hide comment
@iamandrewluca

iamandrewluca 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;
}

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