ES10 (ECMAScript 2019) introduced Array.prototype.flat, Array.prototype.flatMap, Object.fromEntries, and other utility methods.
June 2019
ES10 (ECMAScript 2019) introduced Array.prototype.flat, Array.prototype.flatMap, Object.fromEntries, and other utility methods.
Try out JavaScript code examples and experiment with features in the official TypeScript playground.
Open JavaScript PlaygroundCreates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
const arr = [1, 2, [3, 4, [5, 6]]];
console.log(arr.flat()); // [1, 2, 3, 4, [5, 6]]
console.log(arr.flat(2)); // [1, 2, 3, 4, 5, 6]
console.log(arr.flat(Infinity)); // [1, 2, 3, 4, 5, 6]Maps each element using a mapping function, then flattens the result by one level.
const sentences = ["Hello world", "Good morning"];
const words = sentences.flatMap(sentence => sentence.split(" "));
console.log(words); // ["Hello", "world", "Good", "morning"]
// Equivalent to map().flat()
const words2 = sentences.map(sentence => sentence.split(" ")).flat();Transforms a list of key-value pairs into an object.
const entries = [["name", "John"], ["age", 30]];
const obj = Object.fromEntries(entries);
console.log(obj); // { name: "John", age: 30 }
// With Map
const map = new Map([["a", 1], ["b", 2]]);
const objFromMap = Object.fromEntries(map);
console.log(objFromMap); // { a: 1, b: 2 }