Quirrel4.41.0

types.Array.map

Method on every array
array.map(callback: function): any

Builds a new array from the results of callback on each element.

The binding carries no declaration string, so the VM cannot report parameter names. The names above are from this page; the types and attributes still come from the VM. The VM also cannot tell an optional parameter from a variadic tail here, so read the brackets and any trailing ... from the prose below, not from the signature.

Parameters

callbackfunctioncallback(value, [index], [array]), called for each element, in order

Return value

A new array, one result per source element that was not dropped (see Notes).

Errors

Whatever callback throws, on the first element where it throws, except a thrown null (see Notes).

Notes

callback gets exactly as many of the arguments listed above as it declares parameters for, and never more.

callback may throw null to drop that element instead of contributing to the result, so a filter and a map that can share one pass over the array can be written as one map instead of filter followed by map. This is specific to map: none of the other array iteration methods (each, filter, apply, findindex, findvalue, reduce) give a thrown null any special meaning; there, it aborts like any other thrown value.

Example

examples/types/array/map.nut
let a = [1, 2, 3, 4];
let squares = a.map(function(v) { return v * v });
println("squares =", ", ".join(squares.map(@(v) v.tostring())));
println("squares == a:", squares == a);   // map() always returns a new array

// throwing null inside the callback drops that element instead of failing
let odds = a.map(function(v) { if (v % 2 == 0) throw null; return v });
println("odds =", ", ".join(odds.map(@(v) v.tostring())));
Output:
squares = 1, 4, 9, 16
squares == a: false
odds = 1, 3

See also

applyReplaces every element with the result of callback on it.
filterCollects the elements for which callback returns a true value.
arrayclass index