Array Extensions
v0.1.0The Array Extension methods extend the global Array Object´s Prototype.
Usage
Import the extensions part as early as possible to make sure the global Object Prototypes are extended.
Your IDE might offer the typing without importing this init function as they are declared globally.
import { initArrayExtensions } from '@oardi/ts-utils';
initArrayExtensions();
Initialization is idempotent and keeps the installed methods unchanged. If Array.prototype already has
a foreign own property with one of the extension names, initialization throws before installing any Array
extensions instead of overwriting the existing property.
Array Definition
The following Array operations are being executed on this array:
interface IPerson {
id: number;
name: string;
hobby: string;
}
const persons: Array<IPerson> = [
{ id: 1, name: 'John', hobby: 'Hiking' },
{ id: 2, name: 'Doe', hobby: 'Running' },
{ id: 3, name: 'Marry', hobby: 'Swimming' },
{ id: 4, name: 'Max', hobby: 'Hiking' },
{ id: 5, name: 'Maddy', hobby: 'Swimming' },
{ id: 6, name: 'Pete', hobby: 'Running' },
{ id: 7, name: 'Anna', hobby: 'Hiking' },
];
distinct
persons.map(person => person.hobby).distinct();
// ["Hiking", "Running", "Swimming"]
filterBy
persons.filterBy(person => person.name === 'John');
// [{ id: 1, name: 'John', hobby: 'Hiking' }]
first
Returns the first item. Empty arrays, a missing first slot in a sparse array, and an explicit
undefined first item return null.
persons.first();
// {id: 1, name: "John", hobby: "Hiking"}
[].first();
// null
new Array<number>(1).first();
// null
[undefined].first();
// null
groupBy
Groups entries into a null-prototype record, so every string returned by the selector is treated as a data key.
persons.groupBy(entry => entry.hobby);
// Output:
// Hiking: Array[3]
// Running: Array[2]
// Swimming: Array[2]
orderBy
persons.orderBy(entry => entry.hobby);
orderBy() sorts the original array and returns that same array.
Strings use locale-aware comparison; other values use their relational < and > behavior. null,
undefined, and NaN are treated as missing values and always sorted after comparable values in both
ascending and descending order. Missing or otherwise non-comparable values retain their relative order.
removeBy
persons.removeBy(person => person.id, 1);
removeBy() returns a filtered array without modifying the original array.
Previous:General
← Get startedNext:Extensions
Date Extension →