Skip to content

sort — GTM Variable Template for Array

VARIABLES › ARRAY
sort EXTENDED Array

Returns a sorted array. A custom comparison function can be provided to control the sort order.



Examples

Sort strings alphabetically
INPUT
Array To Sort: ['banana', 'apple', 'cherry', 'date']
Add Comparison Function (Optional): false
Compare Function: null
OUTPUT
['apple', 'banana', 'cherry', 'date']
Empty array unchanged
INPUT
Array To Sort: []
Add Comparison Function (Optional): false
Compare Function: null
OUTPUT
[]

GTM Configuration

This is what you'll see when you open this variable in Google Tag Manager. Hover the icons for details.

sort
Array To Sort
💾 The array to sort the elements.

Supported formats:
  ✓ Array
Advanced Setting
⚖️ Optional comparison function to define sort order. If not provided, items are sorted as strings in ascending order.

Supported formats:
  ✓ Function
Compare Function
Input Setup
Input Function (optional)
⚙️ Optional pre-processing function applied to the input before internal logic (e.g., convert object to string, normalize case). Internal transformations such as case handling will still apply afterward.
Result Handling
Output Function (optional)
⚙️ Optional function to apply to the result before returning it (e.g., str => str + ' €', val => val !== undefined for boolean conversion). Useful for chaining transformations on the output.
Array To Sort array
💡 Type any text to see the result update live
🎯 Using special value — click input to type instead
Test with:
Falsy
Truthy
Compare Function (Optional) function
sort()


Under the Hood

📜 View Implementation Code
/**
* Returns a new array with the elements sorted. Accepts an optional comparison function.
* 
* @param {Array} data.src - The array to sort.
* @param {boolean} data.add - Whether to use a custom comparison function.
* @param {Function} data.cmp - Comparison function to define sort order (used when add is true).
* @param {Function|string} [data.out] - Optional output handler: function to transform result or string with format.
*
* Direct-mode specific parameters:
* @param {Function} [data.pre] - Optional pre-processor function to transform src before sorting.
* 
* @returns {Array} A new sorted array, or an empty array if input is invalid.
*
* @framework ggLowCodeGTMKit
*/
const getType = require('getType');

const sort = function(arr, useCustomCompare, compareFn) {
   if (getType(arr) !== 'array') {
       return [];
   }
   return useCustomCompare && typeof compareFn === 'function' ? arr.slice().sort(compareFn) : arr.slice().sort();
};
const safeFunction = fn => typeof fn === 'function' ? fn : x => x;
const out = safeFunction(data.out);
// ===============================================================================
// sort - Direct mode
// ===============================================================================
const applyCast = (castFn, value) => safeFunction(castFn)(value);
const value = applyCast(data.pre, data.src);
return out(sort(value, data.add, data.cmp));
// ===============================================================================
// sort(...) – Apply Mode
// ===============================================================================
/*
return function(value, useCustomCompare, compareFn) {
   useCustomCompare = data.rp1 ? data.add : useCustomCompare;
   compareFn = data.rp2 ? data.cmp : compareFn;
   return out(sort(value, useCustomCompare, compareFn));
};
*/
🧪 View Test Scenarios (5 tests)
✅ Array of numbers - should sort numerically as strings by default
✅ '[example] Sort strings alphabetically'
✅ Array with custom comparison function - should sort in descending order
✅ '[example] Empty array unchanged'
✅ Non-array input - should return empty array