JavaScript - flatMap() method

revision:


Category : array

The flatMap() method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level.

The flatMap() method maps all array elements and creates a new flat array. It creates a new array from calling a function for every array element. flatMap() does not execute the function for empty elements and does not change the original array.

It is identical to a map() followed by a flat() of depth 1 (arr.map(...args).flat()), but slightly more efficient than calling those two methods separately.

Syntax :

        array.flatMap(callbackFn)
        array.flatMap(callbackFn, thisArg)
        array.flatMap(function(currentValue, index, arr), thisValue)
    

Parameters:

callbackFn, function : a function to execute for each element in the array. It should return an array containing new elements of the new array, or a single non-array value to be added to the new array. The function is called with the following arguments:

element, currentValue : required; the (value of the) current element being processed in the array.
index : optional; the index of the current element being processed in the array.
array : optional; the array "flatMap()" was called upon.

thisArg, thisValue : optional. A value to use as "this" when executing callbackFn. Default value "undefined".

Examples :

            const arr1 = [1, 2, 1];
            const result = arr1.flatMap((num) => (num === 2 ? [2, 2] : 1));
            console.log(result);
            // Expected output: Array [1, 2, 2, 1]
        

Practical examples

example: map() method and flatMap() method

code:
                    div>
                        <p id="flat-1"></p>
                        <p id="flat-2"></p>
                        <p id="flat-3"></p>
                        <p id="flat-4"></p>
                    </div>
                    <script>
                        const arr1 = [1, 2, 3, 4];
                        arr1.map((x) => [x * 2]);
                        // [[2], [4], [6], [8]]
                        document.getElementById("flat-1").innerHTML = "arr1: " + JSON.stringify(arr1); 
                        document.getElementById('flat-2').innerHTML = "new array 1 using map: " + JSON.stringify(arr1.map((x)=>[x*2]));
                        arr1.flatMap((x) => [x * 2]);
                        // [2, 4, 6, 8]
                        document.getElementById('flat-3').innerHTML = "new array 1 using flatMap: " + JSON.stringify(arr1.flatMap((x)=>[x*2]));
                        // only one level is flattened
                        arr1.flatMap((x) => [[x * 2]]);
                        // [[2], [4], [6], [8]]
                        document.getElementById('flat-4').innerHTML = "new array 1 using flatMap flattening one level: " + JSON.stringify(arr1.flatMap((x)=>[[x*2]]));
                    </script>
                

example: adding and removing items during a map.

code:
                    <div>
                        <p id="flat-5"></p>
                        <p id="flat-6"></p>
                        <p id="flat-7"></p>
                        <p id="flat-8"></p>
                    </div>
                    <script>
                        // Let's say we want to remove all the negative numbers and split the odd numbers into an even number and a 1
                        const a = [5, 4, -3, 20, 17, -33, -4, 18];
                        //         |\  \  x   |  | \   x   x   |
                        //        [4,1, 4,   20, 16, 1,       18]
            
                        const result = a.flatMap((n) => {
                            if (n < 0) {
                                return [];
                            }
                            return n % 2 === 0 ? [n] : [n - 1, 1];
                        });
                        console.log(result); // [4, 1, 4, 20, 16, 1, 18]
                        document.getElementById('flat-5').innerHTML = "new array: " + result;
                    </script>
                

example: flatMap() method

code:
                    <div>
                        <p id="flat-9"></p>
                        <p id="flat-10"></p>
                        
                    </div>
                    <script>
                        const myArr = [1, 2, 3, 4, 5,6];
                        document.getElementById("flat-9").innerHTML = "array : " + myArr;
                        const newArr = myArr.flatMap((x) => x * 2);
                        document.getElementById("flat-10").innerHTML = "new array : " + newArr;
                    </script>