0

I am trying to add elements of an array in jsonnet. Can someone post a sample?

Sample input: [0, 1, 2, 3]

output 6

1 Answers1

2

You can use std.foldl() as the "aggregation" function:

local myArray = [0, 1, 2, 3];

std.foldl(function(x, y) (x + y), myArray, 0)
jjo
  • 2,595
  • 1
  • 8
  • 16
  • 1
    For completeness: you can also write your own recursive function which is the most general way to accumulate stuff: `local sum(arr) = local aux(arr, index, acc) = if index < std.length(arr) then aux(arr, index + 1, acc + arr[index]) else acc; aux(arr, 0, 0); sum([1, 2, 3])` Using foldl is the recommended way. – sbarzowski Dec 02 '20 at 18:30