The array or array like object of elements to be searched.
A function that accepts up to three arguments of type ArrPredicateCallbackFn or ArrPredicateCallbackFn2. The predicate function is called for each element in the thArray until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
Optional
thisArg: anyA value to use as this when executing callbackFn. Defaults to the array if not provided.
A shallow copy of a portion of the given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. If no elements pass the test, an empty array will be returned.
0.8.0
function isBigEnough<T>(value: T) {
return value >= 10;
}
const filtered = arrFilter([12, 5, 8, 130, 44], isBigEnough);
// filtered is [12, 130, 44]
const arrayLikeFiltered = arrFilter({ length: 5, 0: 12, 1: 5, 2: 8, 3: 130, 4: 44}, isBigEnough);
// arrayLikeFiltered is [12, 130, 44]
const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
function isPrime(num) {
for (let i = 2; num > i; i++) {
if (num % i === 0) {
return false;
}
}
return num > 1;
}
console.log(arrFilter(array, isPrime)); // [2, 3, 5, 7, 11, 13]
The arrFilter() method creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.
The filter() method is an iterative method. It calls a provided callbackFn function once for each element in an array, and constructs a new array of all the values for which callbackFn returns a truthy value. Array elements which do not pass the callbackFn test are not included in the new array.
callbackFn
is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.The arrFilter() method is a copying method. It does not alter this but instead returns a shallow copy that contains the same elements as the ones from the original array (with some filtered out). However, the function provided as callbackFn can mutate the array. Note, however, that the length of the array is saved before the first invocation of callbackFn. Therefore:
callbackFn
will not visit any elements added beyond the array's initial length when the call to arrFilter() began.callbackFn
will be the value at the time that element gets visited. Deleted elements are not visited.