Array Functions and Properties
Array functions provide powerful ways to manipulate, search, transform, and analyze arrays in expressions. These methods are similar to JavaScript array methods and enable sophisticated array operations without requiring additional Snaps.
Array Literals
Array literals function similar to JavaScript array literals. However, extra commas in array literals are not supported.
Syntax:
["SnapLogic", "Data", "Integration"]
[1, 2, 3, 4, 5]
[$field1, $field2, $field3]
Array Properties
length
The number of elements in an array. This is similar to the JavaScript length property.
$array.length
// Returns: number of elements
[1, 2, 3, 4, 5].length
// Returns: 5
Adding and Removing Elements
concat()
Returns a new array comprised of this array joined with the arrays or values provided as arguments. The concat function also works with Uint8 arrays. This is similar to the JavaScript concat.
$head.concat($middle, $tail)
// Where $head, $middle, and $tail are all arrays
// Returns: A new array containing all three arrays
[1, 2].concat([3, 4], [5, 6])
// Returns: [1, 2, 3, 4, 5, 6]
push()
Adds one or more elements to the end of an array and returns the new length of the array. This is similar to the JavaScript push.
$Array.push("Mobile", "Email")
// Returns: New length of array with elements added at end
[1, 2].push(3, 4)
// Returns: 4 (new length)
pop()
Removes the last element from an array and returns that element. This is similar to the JavaScript pop.
$Array.pop()
// Returns: The last element of the array
[1, 2, 3].pop()
// Returns: 3
shift()
Removes the first element from an array and returns that element. This method changes the length of the array. This is similar to the JavaScript shift.
$Array.shift()
// Returns: The first element from the array
[1, 2, 3].shift()
// Returns: 1
splice()
Lets you remove and insert elements in an array and returns an array containing the elements removed. This is similar to the JavaScript splice.
array.splice(begin, digit, item...)
// Where:
// - begin: index where to start changing the array
// - digit: number of items to remove
// - item: items to insert
$Contacts.splice(2, 0, 'Business')
// Removes nothing, inserts "Business" at index 2
$Contacts.splice(4, 1, 'State')
// Removes 1 element at index 4, inserts "State"
Searching and Finding
indexOf()
Returns the first index at which a given element can be found in the array or -1 if it is not present. This is similar to the JavaScript indexOf.
$Array.indexOf(0)
// Where $Array = [0, 2, 4, 6, 8]
// Returns: 0
$Array.indexOf(1)
// Where $Array = [0, 2, 4, 6, 8]
// Returns: -1 (not found)
lastIndexOf()
Returns the last index at which a given element can be found in the array. This is similar to the JavaScript lastIndexOf.
$first.lastIndexOf(0)
// Where $first = [0, 2, 4, 6, 8]
// Returns: 0
[1, 2, 3, 2, 1].lastIndexOf(2)
// Returns: 3
find()
Returns the first element found for which the given callback returns true. This is similar to the JavaScript Array.find() method.
$myarray.find(x => x > 5)
// Returns: First element whose value is greater than 5
[1, 5, 10, 15].find(x => x > 8)
// Returns: 10
findIndex()
Returns the index of the first element for which the given callback returns true. If no match is found, -1 is returned. This is similar to the JavaScript Array.findIndex() method.
$myarray.findIndex(x => x > 5)
// Returns: Index of first element whose value is greater than 5
[1, 5, 10, 15].findIndex(x => x > 8)
// Returns: 2 (index of 10)
Filtering and Transformation
filter()
Returns a new array containing only the elements for which the given callback returned true. This is similar to the JavaScript Array.filter() method.
$myarray.filter(x => x > 5)
// Returns: New array containing numbers greater than 5
// Remove duplicate entries
$myarray.filter((item, pos, a) => a.indexOf(item) == pos)
// Where $myarray = ["Fred", "Wilma", "Fred", "Betty", "Fred", "Barney"]
// Returns: ["Fred", "Wilma", "Betty", "Barney"]
map()
Returns a new array with the values transformed by the given callback. This is similar to the JavaScript Array.map() method.
$myarray.map(x => x * 10)
// Returns: New array where elements have been multiplied by 10
[1, 2, 3].map(x => x * 2)
// Returns: [2, 4, 6]
$items.map(item => item.name)
// Extracts name property from each object
reduce()
Reduces an array to a single value using the given callback. For each element in the array, the callback is called with four arguments: the accumulated value, the value of the current element, the index of the current element, and the array itself. This is similar to the JavaScript Array.reduce() method.
$myarray.reduce((accum, currentValue) => accum + currentValue, 0)
// Returns: Sum of all elements in the array
[1, 2, 3, 4, 5].reduce((sum, num) => sum + num, 0)
// Returns: 15
// Build object from array
$array.reduce((obj, item) => ({...obj, [item.id]: item}), {})
reduceRight()
Like the reduce() method, except the elements are traversed right-to-left instead of left-to-right. This is similar to the JavaScript Array.reduceRight() method.
$myarray.reduceRight((accum, currentValue) => accum + currentValue, 0)
// Processes array from right to left
["a", "b", "c"].reduceRight((str, char) => str + char, "")
// Returns: "cba"
Sorting and Reversing
sort()
Returns a lexicographically and case-sensitively sorted array, by default. You can leverage other attributes like .compare(), .foreach() to customize these outputs. This is similar to the JavaScript sort.
// Default sort (lexicographic)
[45, 7, 23, 88, 12].sort()
// Returns: [12, 23, 45, 7, 88]
// Numeric ascending sort
$list.sort((a, b) => a - b)
// Where $list = [45, 7, 23, 88, 12]
// Returns: [7, 12, 23, 45, 88]
// Numeric descending sort
$list.sort((a, b) => b - a)
// Returns: [88, 45, 23, 12, 7]
// Case-insensitive string sort
$colors.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()))
// Where $colors = ["Blue", "beige", "Maroon", "cyan"]
// Returns: ["beige", "Blue", "cyan", "Maroon"]
// Sort array of objects by property
$employees.sort((a, b) => a.age - b.age)
// Sorts by age ascending
$employees.sort((a, b) => a.name.localeCompare(b.name))
// Sorts by name alphabetically
reverse()
Transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array. This is similar to the JavaScript reverse.
$Array.reverse()
// Returns: Array in reverse order
[1, 2, 3, 4, 5].reverse()
// Returns: [5, 4, 3, 2, 1]
Extracting and Combining
slice()
Returns a shallow copy of an array containing copies of the original elements. This is similar to the JavaScript slice.
$Array.slice(1, 3)
// Where $Array = [0, 2, 4, 6, 8]
// Returns: [2, 4]
[0, 1, 2, 3, 4].slice(2)
// Returns: [2, 3, 4] (from index 2 to end)
[0, 1, 2, 3, 4].slice(-2)
// Returns: [3, 4] (last 2 elements)
join()
Joins all elements of an array into a string. This is similar to the JavaScript join.
array.join(optSeparator)
// optSeparator: optional string to separate elements (default: comma)
["SnapLogic", "Data", "Integration"].join(" ")
// Returns: "SnapLogic Data Integration"
[1, 2, 3, 4].join("-")
// Returns: "1-2-3-4"
$array.join()
// Uses default comma separator
toString()
Returns one string containing each array element separated by commas. This is similar to the JavaScript toString.
$Array.toString()
// Returns: Comma-separated string of array elements
[1, 2, 3].toString()
// Returns: "1,2,3"
Advanced Transformations
toObject()
Performs arrow functions on the values of the array to generate the key/value pair in the object returned by the callback, and, if given, a second callback.
array.toObject(callback, callback2)
[1, 2, 3, 4].toObject(x => x, x => x * x)
// Returns: {"1":1, "2":4, "3":9, "4":16}
['zero', 'one', 'two'].toObject((x, index) => index, x => x.contains('two'))
// Returns: {"0": false, "1": false, "2": true}
Common Patterns
Remove Duplicates:
$array.filter((item, pos, arr) => arr.indexOf(item) == pos)
Flatten Nested Arrays:
$nestedArray.reduce((flat, item) => flat.concat(item), [])
Group by Property:
$items.reduce((groups, item) => {
const key = item.category;
groups[key] = groups[key] || [];
groups[key].push(item);
return groups;
}, {})
Sum Array Values:
$numbers.reduce((sum, num) => sum + num, 0)
Find Maximum Value:
$numbers.reduce((max, num) => num > max ? num : max, $numbers[0])
Check if All Elements Match:
$array.filter(x => x > 0).length == $array.length
Check if Any Element Matches:
$array.filter(x => x > 0).length > 0
Transform Array of Objects:
$users.map(user => ({
id: user.id,
fullName: user.firstName + " " + user.lastName,
email: user.email
}))
Chunk Array:
// Split array into chunks of size n
$array.reduce((chunks, item, index) => {
const chunkIndex = Math.floor(index / n);
chunks[chunkIndex] = chunks[chunkIndex] || [];
chunks[chunkIndex].push(item);
return chunks;
}, [])
Best Practices
- Immutability: Methods like filter(), map(), and slice() return new arrays rather than modifying the original.
- Performance: For large arrays, consider performance implications of chaining multiple operations.
- Callbacks: Use arrow functions for concise and readable callbacks.
- Initial Values: Always provide an initial value to reduce() to avoid unexpected behavior with empty arrays.
- Sort Comparisons: For numeric sorting, always provide a comparison function (a, b) => a - b.
- Null Safety: Check array length before accessing elements to avoid null/undefined errors.
- Index Validation: indexOf() returns -1 when not found; check this before using the result.
- Method Chaining: Chain array methods for complex transformations: array.filter().map().reduce().
Method Comparison
| Method | Purpose | Returns | Mutates Array |
|---|---|---|---|
filter() |
Keep matching elements | New array | No |
map() |
Transform elements | New array | No |
reduce() |
Reduce to single value | Any type | No |
find() |
Find first match | Element or undefined | No |
findIndex() |
Find first match index | Number (-1 if not found) | No |
indexOf() |
Find element position | Number (-1 if not found) | No |
slice() |
Extract portion | New array | No |
concat() |
Combine arrays | New array | No |
join() |
Convert to string | String | No |
sort() |
Sort elements | Same array | Yes |
reverse() |
Reverse order | Same array | Yes |
push() |
Add to end | New length | Yes |
pop() |
Remove from end | Removed element | Yes |
shift() |
Remove from start | Removed element | Yes |
splice() |
Remove/insert elements | Removed elements | Yes |