The Array Helper Library provides a collection of utility functions for working with arrays, including searching, transformation, sorting, and validation.
To install the package, use:
npm install @jlhv/array-helper
Import the required functions from the library:
import { unique, flatten, shuffle, min, max } from "@jlhv/array-helper";
Checks if an array is empty.
isEmpty([]); // true
isEmpty([1, 2, 3]); // false
Gets the first element of an array.
first([10, 20, 30]); // 10
first([]); // undefined
Gets the last element of an array.
last([10, 20, 30]); // 30
last([]); // undefined
Removes duplicate values from an array.
unique([1, 2, 2, 3, 3, 4]); // [1, 2, 3, 4]
Finds the index of an element in an array without using indexOf
.
indexOf([5, 10, 15], 10); // 1
indexOf([5, 10, 15], 20); // -1
Checks if an array contains a specific value.
contains([1, 2, 3], 2); // true
contains([1, 2, 3], 5); // false
Counts the occurrences of a value in an array.
countOccurrences([1, 2, 2, 3, 3, 3], 3); // 3
Merges two arrays without duplicates.
mergeUnique([1, 2, 3], [3, 4, 5]); // [1, 2, 3, 4, 5]
Flattens a nested array (single level).
flatten([1, [2, 3], 4]); // [1, 2, 3, 4]
Finds common elements between two arrays.
intersection([1, 2, 3], [2, 3, 4]); // [2, 3]
Finds elements that are in the first array but not in the second.
difference([1, 2, 3], [2, 3, 4]); // [1]
Shuffles an array without using built-in functions.
shuffle([1, 2, 3, 4]); // Output may vary
Reverses an array without using reverse()
.
reverse([1, 2, 3]); // [3, 2, 1]
Sorts an array using bubble sort.
bubbleSort([5, 3, 8, 1]); // [1, 3, 5, 8]
Finds the minimum value in an array.
min([3, 1, 4, 1, 5]); // 1
Finds the maximum value in an array.
max([3, 1, 4, 1, 5]); // 5
Groups elements based on a callback.
groupBy(["apple", "banana", "avocado"], (fruit) => fruit[0]);
// { a: ["apple", "avocado"], b: ["banana"] }
Splits an array into two groups based on a condition.
partition([1, 2, 3, 4], (num) => num % 2 === 0);
// [[2, 4], [1, 3]]
Breaks an array into chunks of a given size.
chunk([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]]
Removes falsy values (false, null, 0, "", undefined, NaN).
compact([0, 1, false, 2, "", 3]); // [1, 2, 3]
Rotates an array by n
positions.
rotate([1, 2, 3, 4, 5], 2); // [3, 4, 5, 1, 2]
rotate([1, 2, 3, 4, 5], -2); // [4, 5, 1, 2, 3]
Returns a random element from an array.
randomElement([10, 20, 30]); // Output may vary
Gets the nth element of an array (supports negative indexing).
nth([10, 20, 30], 1); // 20
nth([10, 20, 30], -1); // 30
Finds unique elements across multiple arrays.
uniqueMultiple([1, 2, 3], [2, 3, 4], [3, 4, 5]); // [1, 5]
ISC License.
Vijayavel R