Skip to content

Instantly share code, notes, and snippets.

@Jakobud
Created April 25, 2017 20:12
Show Gist options
  • Save Jakobud/ec056b52f3673cc369dc97f2c2428424 to your computer and use it in GitHub Desktop.
Save Jakobud/ec056b52f3673cc369dc97f2c2428424 to your computer and use it in GitHub Desktop.
Removed an item for a SASS list based on it's index (mimics behavior of the native map-remove function)
/// list-remove
/// Remove an item from a list
/// @param $list - A SASS list
/// @param $index - The list index to remove
/// @returns A SASS list
/// @author Jake Wilson <jake.e.wilson@gmail.com>
@function list-remove($list, $index) {
$newList: ();
@for $i from 1 through length($list) {
@if $i != $index {
$newList: append($newList, nth($list,$i), 'space');
}
}
@return $newList;
}
@jakob-e
Copy link

jakob-e commented Sep 27, 2018

Thanks for sharing :)

Here is a version that allows you to use a negative n value to remove from the back of the list
and also takes into account the list separator and if the list is bracketed

@function nth-delete($list, $n){
    $result: ();
    $n: if($n < 0, length($list) + $n + 1, $n);
    $bracketed: is-bracketed($list);
    $separator: list-separator($list);
    @for $i from 1 through length($list){
        @if $i != $n { $result: append($result, nth($list, $i)); }
    }
    @return join((), $result, $separator, $bracketed);
}
nth-delete( (foo bar baz qux), 2 )     =>  foo baz qux
nth-delete( (foo, bar, baz, qux), 2 )  =>  foo, baz, qux
nth-delete( [foo bar baz qux], 2 )     =>  [foo baz qux]
nth-delete( [foo, bar, baz, qux], 2 )  =>  [foo, baz, qux]

nth-delete( (foo bar baz qux), -2 )    =>  foo bar qux
nth-delete( (foo, bar, baz, qux), -2 ) =>  foo, bar, qux
nth-delete( [foo bar baz qux], -2 )    =>  [foo bar qux]
nth-delete( [foo, bar, baz, qux], -2 ) =>  [foo, bar, qux]

@kerryj89
Copy link

kerryj89 commented Oct 2, 2021

Thank you both for this. Surprised this function doesn't exist natively yet.

@Jikol
Copy link

Jikol commented Mar 28, 2022

I don't want to be nitpicky, but... Sass not SASS

/// @param $list - A SASS list
/// @returns A SASS list

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment