zipWithIndex
Takes a list of values, pairs each value with its index number, and returns a list of pairs.
Zero-based indexing applies, so the first value is paired with 0, the second is paired with 1, and so on.
The function can take a list-like object, so it also works on columns, rows, and arrays.
Parameters
LIST (list, column, row, or JSON array)
The input list or list-like object.
Examples
ATL in Script | Resulting List | Printed Result |
---|---|---|
[[ myList = makeList('A','B','C') zipWithIndex(myList) ]] | ( (A, 0), (B, 1), (C, 2) ) | A and 0, B and 1 and C and 2 |
Note
For simplicity, this example applies zipWithIndex
to a hard-coded list. Typically, the input is a list-like object such as a JSON array. See the next example for guidance.
Assume a "Describe a JSON Object" project with this data:
{ "yr2022": [ {"branch": "Atlanta", "sales": 1724881.72, "profit": 94293.34}, {"branch": "Chicago", "sales": 2473912.44, "profit": 83069.52}, {"branch": "Detroit", "sales": 2419317.35, "profit": 94543.18}, {"branch": "Phoenix", "sales": 1782178.66, "profit": 84782.76} ] }
The "yr2022" array contains four JSON objects. Each object contains three key–value pairs.
You could sort the objects by sales in descending order, then apply zipWithIndex
to the sorted result.
[[ sortedBySales = sort(WholeJSON.yr2022, (x,y) -> sign(y.sales - x.sales)) zipWithIndex(sortedBySales) ]]
The printed output is:
|
The first value in each pair is a JSON object, and the second is its index number. Note that the pairs are sorted by the object's sales value in descending order.
Suppose you want to generate narrative text for each object but vary the output depending on its place in the sorted list. You can do this by referencing the index numbers in a conditional. Here's an example:
[[ sortedBySales = sort(WholeJSON.yr2022, (x,y) -> sign(y.sales - x.sales)) results = zipWithIndex(sortedBySales) map(results, x -> "[[if(x[1]==0){1st = [[x[0].branch]] ([[abbreviateNumber(currencyFormat(x[0].sales))]])} elseif(x[1]==1){2nd = [[x[0].branch]] ([[abbreviateNumber(currencyFormat(x[0].sales))]])} elseif(x[1]==2){3rd = [[x[0].branch]] ([[abbreviateNumber(currencyFormat(x[0].sales))]])} else{4th = [[x[0].branch]] ([[abbreviateNumber(currencyFormat(x[0].sales))]])}]]") ]]
The map function iterates through results
, applying a lambda expression to each pair. The lambda is a conditional statement that ensures the output varies depending on the pair's index number.
The output text is:
1st = Chicago ($2.47m), 2nd = Detroit ($2.42m), 3rd = Phoenix ($1.78m) and 4th = Atlanta ($1.72m)