← Download MyJS
MyJS block · Arrays
filterMap 1.0.0
Maps an array and leaves out the items you skip, in one pass. To leave an item out, return the skip value passed to your function. Every other result is kept, even undefined.
- Exports
-
filterMap - Works in
- Browser and Node.js
- Tags
- map filter array flatMap compactMap
The code of version 1.0.0
/**
* Calls a function on each item of an array and returns the results, leaving
* out any item the function skips. It's like `map` and `filter` in one pass.
* To skip an item, return the `skip` value that the function is given as its
* fourth argument. Every other result is kept, including `undefined`.
* @template T, U
* @param {ArrayLike.<T>} arr
* The array, or array-like object (such as a string or a NodeList), to go
* through.
* @param {function(T, number, ArrayLike.<T>, Object): U} fn
* Called with each item, its index, `arr` and `skip`. Returns the value to
* keep, or `skip` to leave the item out.
* @returns {Array.<U>}
* The results of `fn`, in order, without the items it skipped.
*
* @example <caption>Map and filter in one pass</caption>
* filterMap([1, 2, 3, 4], (n, i, arr, skip) => n % 2 ? skip : n * 10);
* // → [20, 40]
*
* @example <caption>Keeping only the numbers</caption>
* filterMap(['1', 'two', '3'], (s, i, arr, skip) => {
* const n = Number(s);
* return Number.isNaN(n) ? skip : n;
* });
* // → [1, 3]
*
* @example <caption>undefined is kept like any other value</caption>
* filterMap([1, undefined, 2], (x, i, arr, skip) => x === 2 ? skip : x);
* // → [1, undefined]
*/
function filterMap(arr, fn) {
// A new object each call, so nothing a caller returns can match it by accident
var skip = {};
var ret = [];
for (var i = 0, l = arr.length; i < l; i++) {
var result = fn(arr[i], i, arr, skip);
if (result !== skip) {
ret.push(result);
}
}
return ret;
}
Versions
-
1.0.0 Oct 22, 2026
Initial