unique()

Returns an array with duplicate elements removed.

Syntax

unique(ARRAY)

Parameters

ARRAY
The array or collection from which to remove duplicate elements. If a single value is specified, an array containing only that value is returned.

Description

The unique() function removes duplicate elements from the input array and returns an array containing only unique elements. Duplicate detection is based on element equality.

The order of elements in the returned array is not guaranteed. If a single non-array value is passed as an argument, an array containing only that value is returned. If the input is null, null is returned.

Error codes

N/A

Usage examples

  1. Remove duplicate elements from an array (order of returned elements is not guaranteed)

    json "{}" | eval result = unique(array(1, 1, 2, 3, 2))
    | # result: [1, 2, 3]
    
  2. Values of different types are treated as distinct elements

    json "{}" | eval result = unique(array(1, "1", 2, "2"))
    | # result: [1,"1",2,"2"]
    
  3. Passing a single value returns an array containing only that value

    json "{}" | eval result = unique("hello")
    | # result: ["hello"]
    
  4. null input

    json "{}" | eval result = unique(null)
    | # result: null
    

Compatibility

unique() has been available since before Sonar 4.0.