@each loop with index

SassEach

Sass Problem Overview


I was wondering if you can get an element index for the @each loop.

I have the following code, but I was wondering if the $i variable was the best way to do this.

Current code:

$i: 0;
$refcolors: #55A46A, #9BD385, #D9EA79, #E4EE77, #F2E975, #F2D368, #F0AB55, #ED7943, #EA4E38, #E80D19;

@each $c in $refcolors {
    $i: $i + 1;
    #cr-#{$i} strong {
        background:$c;
    }   
}

Sass Solutions


Solution 1 - Sass

First of all, the @each function is not from Compass, but from Sass.


To answer your question, this cannot be done with an each loop, but it is easy to convert this into a @for loop, which can do this:

@for $i from 1 through length($refcolors) {
    $c: nth($refcolors, $i);

    // ... do something fancy with $c
}

Solution 2 - Sass

To update this answer: yes you can achieve this with the @each loop:

$colors-list: #111 #222 #333 #444 #555;

@each $current-color in $colors-list {
    $i: index($colors-list, $current-color);
    .stuff-#{$i} { 
        color: $current-color;
    }
}

Source: http://12devs.co.uk/articles/handy-advanced-sass/

Solution 3 - Sass

Sometimes you may need to use an array or a map. I had an array of arrays, i.e.:

$list = (('sub1item1', 'sub1item2'), ('sub2item1', 'sub2item2'));

I found that it was easiest to just convert it to an object:

$list: (
    'name': 'thao',
    'age': 25,
    'gender': 'f'
);

And use the following to get $i:

@each $property, $value in $list {
    $i: index(($list), ($property $value));

The sass team also recommended the following, although I'm not much of a fan:

> [...] The above code is how I'd like to address this. It can be made more efficient by adding a Sass function like range($n). So that range(10) => (1, 2, 3, 4, 5, 6, 7, 8, 9, 10). Then enumerate can become:

@function enumerate($list-or-map) {
    @return zip($list-or-map, range(length($list-or-map));
}

link.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionignacioricciView Question on Stackoverflow
Solution 1 - SassWouter JView Answer on Stackoverflow
Solution 2 - SassJimmerz28View Answer on Stackoverflow
Solution 3 - Sassnikk wongView Answer on Stackoverflow