ES14 (ECMAScript 2023) introduced Array grouping methods, WeakMap and WeakSet improvements, and Array.prototype.toSorted.
June 2023
ES14 (ECMAScript 2023) introduced Array grouping methods, WeakMap and WeakSet improvements, and Array.prototype.toSorted.
Try out JavaScript code examples and experiment with features in the official TypeScript playground.
Open JavaScript PlaygroundGroup array elements by a key function into objects or maps.
const people = [
{ name: "John", age: 25, city: "NYC" },
{ name: "Jane", age: 30, city: "LA" },
{ name: "Bob", age: 25, city: "NYC" },
{ name: "Alice", age: 30, city: "LA" }
];
// Group by age
const byAge = people.groupBy(person => person.age);
console.log(byAge);
// { 25: [{ name: "John", age: 25, city: "NYC" }, { name: "Bob", age: 25, city: "NYC" }],
// 30: [{ name: "Jane", age: 30, city: "LA" }, { name: "Alice", age: 30, city: "LA" }] }
// Group by city into a Map
const byCity = people.groupByToMap(person => person.city);
console.log(byCity); // Map with city keysReturns a new sorted array without modifying the original.
const numbers = [3, 1, 4, 1, 5, 9];
const sorted = numbers.toSorted();
console.log(sorted); // [1, 1, 3, 4, 5, 9]
console.log(numbers); // [3, 1, 4, 1, 5, 9] (unchanged)
// With compare function
const users = [
{ name: "John", age: 30 },
{ name: "Jane", age: 25 },
{ name: "Bob", age: 35 }
];
const byAge = users.toSorted((a, b) => a.age - b.age);
console.log(byAge); // Sorted by ageReturns a new reversed array without modifying the original.
const arr = [1, 2, 3, 4, 5];
const reversed = arr.toReversed();
console.log(reversed); // [5, 4, 3, 2, 1]
console.log(arr); // [1, 2, 3, 4, 5] (unchanged)Returns a new array with the element at the given index replaced.
const arr = [1, 2, 3, 4, 5];
const newArr = arr.with(2, 10);
console.log(newArr); // [1, 2, 10, 4, 5]
console.log(arr); // [1, 2, 3, 4, 5] (unchanged)
// With negative index
const newArr2 = arr.with(-1, 100);
console.log(newArr2); // [1, 2, 3, 4, 100]