What's new in ECMAScript 2019 (ES2019) / ES10

Array.flat()

Array.flat() returns a new array with any sub-array(s) flattened. A call to Array.flat() without any arguments will only flatten one-level deep. An optional depth argument can be provided or it can just be called consecutively.

let arr = [1, 2, 3, [4, 5, 6, [7, 8, 9, [10, 11, 12]]]];
arr.flat(); // [1, 2, 3, 4, 5, 6, Array(4)];
arr.flat().flat(); // [1, 2, 3, 4, 5, 6, 7, 8, 9, Array(3)];
arr.flat(3); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
// Or, if you're not sure about the depth of the array:
arr.flat(Infinity); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Array.flatMap()

The flatMap() method is identical to the ES6 map method, but also flattens at the same time. The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. flatMap() is often quite useful, as merging both into one method is slightly more efficient.

let arr = [1, 2, 3, 4, 5];
arr.map(x => [x, x * 2]);
// [Array(2), Array(2), Array(2)]
// 0: (2)[1, 2]
// 1: (2)[2, 4]
// 2: (2)[3, 6]
arr.flatMap(v => [v, v * 2]);
// [1, 2, 2, 4, 3, 6, 4, 8, 5, 10]

String.trimStart() & String.trimEnd()

String.trimStart() can be used to trim white space from the start of a string.

let  greeting =  "    Hello everyone";
console.log(greeting.trimStart());
// "Hello everyone"

let greeting = "Hello world    ";

console.log(greeting.trimEnd());
// "Hello world"

Comments