arrayFilter

Used to filter an array to items for which the closure function returns true.

arrayFilter(array array, function(item, [index, [array]]) closure, [boolean parallel], [number maxThreads]) → returns array

Member Function Syntax

someArray.filter(function(item, [index, [array]]), [boolean parallel], [number maxThreads]);

Argument Reference for the arrayFilter function

array

Required: Yes

function

Required: Yes
Inline closure function executed for each element in the array. Returns true if the array element should be included in the filtered array. Support for passing the original array to the closure function added in CF11 Update 5.

parallel

Required: No
Default: false
Lucee only option, true or false if the items can be executed in parallel

maxThreads

Required: No
Default: 20
Lucee only option, the number of threads to use when parallel = true

Links more information about arrayFilter

Examples sample code invoking the arrayFilter function


Example using a simple numeric comparison

Take an array of struct items and use arrayFilter to return ones of a rating 3 and higher.

fruitArray = [{fruit='apple', rating=4}, {fruit='banana', rating=1}, {fruit='orange', rating=5}, {fruit='mango', rating=2}, {fruit='kiwi', rating=3}];

favoriteFruits = arrayFilter(fruitArray, function(item){
     return item.rating >= 3;
});
writedump(favoriteFruits);

Expected Result: Array with the structs for apple, orange and kiwi.


Example using a member function

This is the same example as above, but using a member function on the array instead of a standalone function.

fruitArray = [{fruit='apple', rating=4}, {fruit='banana', rating=1}, {fruit='orange', rating=5}, {fruit='mango', rating=2}, {fruit='kiwi', rating=3}];

favoriteFruits = fruitArray.filter(function(item){
     return item.rating >= 3;
});
writedump(favoriteFruits);

Expected Result: Array with the structs for apple, orange and kiwi.


Fork me on GitHub