Design

Sorting arrays

Sort your data
COMMUNITY FEATURE Available for:
Carbone Cloud
Carbone On-premise
Embedded Carbone JS
  v2.0+ 

Ascendant sort

Carbone allows to use attributes of objects instead of the reserved iterator i to iterate over arrays. This can be used to sort data directly in the template.

In this example, all cars are first sorted by power in ascending order, and if two items have the same power value, they are sorted by item position in the array i.

data
{
  "cars" : [
    { "brand" : "Ferrari" , "power" : 3 },
    { "brand" : "Peugeot" , "power" : 1 },
    { "brand" : "BMW"     , "power" : 2 },
    { "brand" : "Lexus"   , "power" : 1 }
  ]
}
template
Cars{d.cars[power  , i].brand}{d.cars[power+1, i+1].brand}
Carbone Merge Icon
result
CarsPeugeotLexusBMWFerrari

Multiple sort attributes

Multiples attributes can be used to sort data.

Here is an example to sort the array by power, sub.size, and array position i:

data
{
  "cars" : [
    { "brand" : "Ferrari" , "power" : 3, "sub" : { "size" : 1  }  },
    { "brand" : "Aptera"  , "power" : 1, "sub" : { "size" : 20 }  },
    { "brand" : "Peugeot" , "power" : 1, "sub" : { "size" : 20 }  },
    { "brand" : "BMW"     , "power" : 2, "sub" : { "size" : 1  }  },
    { "brand" : "Kia"     , "power" : 1, "sub" : { "size" : 10 }  }
  ]
}
template
Cars{d.cars[power  , sub.size  , i].brand}{d.cars[power+1, sub.size+1, i+1].brand}
Carbone Merge Icon
result
CarsKiaApteraPeugeotBMWFerrari

Descendant Sort

Coming soon in Carbone v5