JavaScript array flatMap() method is used to map all array elements and then flattens it into a new array. This method is a combination of map() and flat() methods and doesn’t modify the original array.
Syntax
let new_array = arr.flatMap(function callback(currentValue[, index[, array]]) {
// return element for new_array
}[, thisArg])
Parameters
- currentValue(required): It is the current element being processed in the array.
- index(optional): It is the index of the current element being processed in the array.
- array(optional): It is the array on which the map() function is called.
thisValue(optional): It is a value to use as this when executing the function.
Return Value
It returned a new array with each element resulting from the callback function and flattened to a depth 1.
Visual Representation
Example 1: How to Use Array flatMap() method
let arrA = [1, 2, 3, 4];
let arrB = arrA.flatMap(x => [x + 2]);
console.log(arrB);
let arrC = arrA.flatMap(x => [x * 2]);
console.log(arrC);
let arrD = arrA.flatMap(x => [x - 1]);
console.log(arrD);
Output
[ 3, 4, 5, 6 ]
[ 2, 4, 6, 8 ]
[ 0, 1, 2, 3 ]
Example 2: Generate a list of words from a list of sentences
const arr1 = ["Hello world", "", "My friend"];
console.log(arr1.map((x) => x.split(" ")));
console.log(arr1.flatMap((x) => x.split(" ")));
Output
[ [ 'Hello', 'world' ], [ '' ], [ 'My', 'friend' ] ]
[ 'Hello', 'world', '', 'My', 'friend' ]
Example 3: Using sparse arrays
const arr1 = [1, 2, , 19, 21];
console.log(arr1.flatMap((x) => [x, x * 2]));
console.log(arr1.flatMap((x) => [, x * 2]));
Output
[
1, 2, 2, 4,
19, 38, 21, 42
]
[ 2, 4, 38, 42 ]
Example 4: Calling flatMap() on non-array objects
const arrayLike = {
length: 3,
0: 11,
1: 19,
2: 21,
};
console.log(Array.prototype.flatMap.call(arrayLike, (x) => [x, x * 2]));
// Array-like objects returned from the callback won't be flattened
console.log(
Array.prototype.flatMap.call(arrayLike, (x) => ({
length: 1,
0: x,
})),
);
Output
[ 11, 22, 19, 38, 21, 42 ]
[
{ '0': 11, length: 1 },
{ '0': 19, length: 1 },
{ '0': 21, length: 1 }
]
Browser Compatibility
- Google Chrome 69 and above
- Edge 79 and above
- Firefox 62 and above
- Opera 56 and above
- Safari 12 and above
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.