sumarray()

Returns the sum of all numeric elements contained in an array.

Syntax

sumarray(ARRAY)

Parameters

ARRAY
The array whose numeric elements are to be summed.

Description

The sumarray() function iterates over each element in the array and returns the sum of elements that are numeric. Non-numeric elements and null elements are excluded from the calculation.

The return type depends on the type of the input value. If the elements are a primitive array of byte, int, long, or short types, a 64-bit integer (long) is returned. If the elements are a primitive array of double or float types, a List, or an object array containing numbers, a 64-bit floating-point number (double) is returned.

If the input is null, null is returned. If all elements in the array are non-numeric or null, 0 (or 0.0) is returned.

Error codes

N/A

Usage examples

  1. Calculate the sum of an integer array

    json "{}" | eval sum = sumarray(array(1, 2, 3, 4, 5))
    | # sum: 15.0
    
  2. Calculate the sum while excluding non-numeric elements and null

    json "{}" | eval sum = sumarray(array(1, 2, 3, null, "a", 4, 5))
    | # sum: 15.0
    
  3. All elements are non-numeric or null

    json "{}" | eval sum = sumarray(array(null, null, "a", "b"))
    | # sum: 0.0
    
  4. null input

    json "{}" | eval sum = sumarray(null)
    | # sum: null
    

Compatibility

sumarray() has been available since before Sonar 4.0.