Skip to content

flatten — GTM Variable Template for Array

VARIABLES › ARRAY
flatten EXTENDED Array

Flattens a nested array into a single-level array.



Examples

Flatten nested arrays
INPUT
Values to Flatten: [{val: ['apple', 'banana']}, {val: ['orange']}]
OUTPUT
['apple', 'banana', 'orange']
Empty array unchanged
INPUT
Values to Flatten: []
sep: ,
OUTPUT
[]

GTM Configuration

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

flatten
Values to Flatten
💾 A list of values to flatten. Each row can contain an array or a single value. Arrays will be unpacked one level deep.

Supported formats:
  ✓ Array: ["a", "b", "c"]
  ✓ Single value: "x", 123, true
  ✓ Variable reference

*** Flatten nested arrays***

*** Empty array unchanged***
Input Setup
Input Function (optional)
⚙️ Optional pre-processing function applied to the extracted values array before flattening (e.g., filter values, transform array). Note: Values are extracted from the table's val property before this function is applied.
Result Handling
Output Function (optional)
⚙️ Optional function to apply to the flattened array before returning it (e.g., arr => arr.filter(v => v), arr => arr.slice(0, 5)). Useful for chaining transformations on the output.
Values to Flatten list
flatten()


Under the Hood

📜 View Implementation Code
/**
 * Flattens nested arrays into a single array (one level deep).
 *
 * @param {Array} data.src - A list of objects with a `val` property (Direct mode) or plain values (Apply mode).
 * @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 processing.
 * 
 * @returns {Array} A flat array of all values.
 *
 * @framework ggLowCodeGTMKit
 */
const getType = require('getType');

const flatten = function(paramList) {
    const list = paramList || [];
    const result = [];
    
    for (let i = 0; i < list.length; i++) {
        const val = list[i];
        if (val === null || val === undefined) continue;
        
        const type = getType(val);
        if (type === 'array') {
            for (let j = 0; j < val.length; j++) {
                result.push(val[j]);
            }
        } else {
            result.push(val);
        }
    }
    return result;
};
const safeFunction = fn => typeof fn === 'function' ? fn : x => x;
const out = safeFunction(data.out);
// ===============================================================================
// flatten - Direct mode
// ===============================================================================
const extractItemValues = (items) => items.map(item => item ? item.val : null);
const applyCast = (castFn, value) => safeFunction(castFn)(value);
const extractedValues = extractItemValues(data.src);
const value = applyCast(data.pre, extractedValues);
return out(flatten(value));
// ===============================================================================
// flatten() – Apply Mode
// ===============================================================================
/*
return function(value) {
   return out(flatten(value));
};
*/
🧪 View Test Scenarios (6 tests)
✅ '[example] Flatten nested arrays'
✅ Test flattening with mixed arrays and single values
✅ Test with null and undefined values
✅ Test with non-string, non-array values (numbers, booleans)
✅ '[example] Empty array unchanged'
✅ Test with nested arrays (one level only)