Published | 15/11/2020 |
---|---|
Last Updated | 17/11/2024 |
let arr = [1, 2, 3, [4, 5, 6, [7, 8, 9, [10, 11, 12]]]];
arr.flat();
// [1, 2, 3, 4, 5, 6, [7, 8, 9, [10, 11, 12]]]
arr.flat().flat();
// [1, 2, 3, 4, 5, 6, 7, 8, 9, [10, 11, 12]]
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]
Reference: MDN web docs - Array.prototype.flat()
let arr = [1, 2, 3, 4];
arr.map(x => [x, x * 2]);
// [[1, 2], [2, 4], [3, 6], [4, 8]]
arr.flatMap(x => [x, x * 2]);
// [1, 2, 2, 4, 3, 6, 4, 8]
Reference: MDN web docs - Array.prototype.flatMap()
const greeting = ' Hello world! ';
console.log(`"${greeting.trimStart()}"`);
// expected output: " Hello world! ";
console.log(`"${greeting.trimStart()}"`);
// expected output: "Hello world! ";
console.log(`"${greeting.trimEnd()}"`);
// expected output: " Hello world!";
References:
MDN web docs - String.prototype.trimStart()\
MDN web docs - String.prototype.trimEnd()
Before ES2019
try {
// do something that raises exception
} catch (err) {
// err is required even if it is not being used in catch block
}
With ES2019
try {
// do something that raises exception
} catch {
// no binding required if it is not being used
}
// Iterable object such as Array or Map
const entries = [
['foo', 'bar'],
['baz', 42]
];
const obj = Object.fromEntries(entries);
console.log(obj);
// expected output: Object { foo: "bar", baz: 42 }
Reference: MDN web docs - Object.fromEntries()