arrayFilter

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

arrayFilter(array, function(item [,index, array]){} [, parallel] [, maxThreads]) → returns array

Member Function Syntax

someArray.filter(function(item [,index, array]){} [, parallel] [, maxThreads])

Argument Reference

array array
Required

callback boolean
Required

Closure or a function reference that will be called for each of the iteration. 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.

Callback parameters:

  • value*any : The value for the current iteration
  • index*numeric : The current index for the iteration
  • array*array : A reference of the original array

parallel boolean
Default: false

Lucee 4.5+ true if the items can be executed in parallel
Values:
  • true
  • false

maxThreads numeric
Default: 20

Lucee 4.5+ the maximum number of threads to use when parallel = true

Links more information about arrayFilter

Examples
Sample code invoking the arrayFilter function

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(serializeJSON(favoriteFruits));

Expected Result: [{"fruit":"apple","rating":4},{"fruit":"orange","rating":5},{"fruit":"kiwi","rating":3}]

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(serializeJSON(favoriteFruits));

Expected Result: [{"fruit":"apple","rating":4},{"fruit":"orange","rating":5},{"fruit":"kiwi","rating":3}]

Signup for cfbreak to stay updated on the latest news from the ColdFusion / CFML community. One email, every friday.

Fork me on GitHub