Lightweight TypeScript extensions for the Array prototype. Adds powerful utility methods for everyday array manipulation.
npm install @mdgfox/array-extensionsImport the package once at the entry point of your application to extend the global Array interface:
import '@mdgfox/array-extensions';const arr = [1, 2, 3, 4, 5];
// shuffle
console.log(arr.shuffle());
// Get random element
console.log(arr.random());
// Get random element (cloned copy)
console.log(arr.randomDeepCopy());// Move elements
const arr = ['a', 'b', 'c'];
arr.move(0, 2); // ['b', 'c', 'a']// Cleanup
const data = [1, null, 0, undefined, 2];
data.compact(); // [1, 0, 2]// Unique objects
const items = [{id: 1}, {id: 2}, {id: 1}];
items.uniqueBy('id'); // [{id: 1}, {id: 2}]Shuffles the array in place using the Fisher–Yates algorithm. Returns the instance for chaining.
Returns a random element from the array by reference. Returns undefined if empty.
Returns a deep-cloned copy of a random element using structuredClone (with a JSON fallback).
Moves an element from one index to another in place. Supports negative indices.
Returns a new array with all null and undefined values removed. (Preserves 0, false, and "").
Returns a new array containing only unique elements (removes duplicates).
Returns a new array containing unique elements based on a specific object key. Useful for de-duplicating arrays of objects.
This library extends the global Array.prototype using Object.defineProperty.
- Enumerable: All added methods are set to
enumerable: false. This ensures that they do not appear infor...inloops orObject.keys()calls, keeping your arrays "clean" and behaving exactly like native JavaScript methods. - Safety: The library checks for the existence of a method before adding it, ensuring compatibility with future ECMAScript standards and other libraries.
- TypeScript: Full type support is included via
declare global.