@rbxts/jsnatives
Array.flatMap
Maps each element using a mapping function, then flattens the result into a new array.
Signature
function flatMap<T, U>( array: Array<T>, func: (item: T, index: number, array: ReadonlyArray<T>) => ReadonlyArray<U> | U): Array<U>
Description
The Array.flatMap()
method first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map()
followed by a flat()
of depth 1, but slightly more efficient.
The mapping function takes three arguments:
item
: The current element being processedindex
: The index of the current elementarray
: The array that flatMap was called upon
Examples
Basic usage
const array = [1, 2, 3];const result = ArrayUtils.flatMap(array, (x) => [x, x * 2]);print(result); // [1, 2, 2, 4, 3, 6]
Comparing map().flat() vs flatMap()
const array = [1, 2, 3];
// Using map() followed by flat()const result1 = ArrayUtils.flat(array.map((x) => [x, x * 2]));print(result1); // [1, 2, 2, 4, 3, 6]
// Using flatMap() (same result, but more efficient)const result2 = ArrayUtils.flatMap(array, (x) => [x, x * 2]);print(result2); // [1, 2, 2, 4, 3, 6]
Using the index parameter
const array = [1, 2, 3];const result = ArrayUtils.flatMap(array, (x, i) => [x, i]);print(result); // [1, 0, 2, 1, 3, 2]
Filtering and mapping in one operation
const array = [1, 2, 3, 4, 5];
// Remove odd numbers and double the even onesconst result = ArrayUtils.flatMap(array, (x) => x % 2 === 0 ? [x * 2] : []);print(result); // [4, 8]
Working with objects
const users = [ { name: "John", hobbies: ["reading", "swimming"] }, { name: "Jane", hobbies: ["painting"] }, { name: "Bob", hobbies: ["gaming", "cooking", "cycling"] }];
// Get all hobbies in a flat arrayconst allHobbies = ArrayUtils.flatMap(users, (user) => user.hobbies);print(allHobbies); // ["reading", "swimming", "painting", "gaming", "cooking", "cycling"]