Frontfire documentation

ArrayList

Version 2.1.0

No search results

Introducing: the JavaScript Array in frustration-free packaging!

What?

The ArrayList class implements a comfortable array collection. It uses a JavaScript Array as its internal storage and provides a public interface inspired by .NET’s List and LINQ Enumerable types with a few more methods of JavaScript’s Array, SQL (relational) group, join and set operations, and others. (It still returns independent arrays from each operation, so it doesn’t have the advantages of IEnumerable. There are other and larger projects for that.)

It borrows its name from the ArrayList class of .NET 1.1 which was mostly replaced by the generic (statically typed) List<T> class in .NET 2.0. This is a good fit again for the dynamically-typed nature of JavaScript.

Why?

JavaScript arrays are historically a constant source of frustration. The Array class tries to be a list, a queue and a stack all in one but does nothing right. It has improved a little over the years, yet some basic operations like removing an item are still missing. Names are also confusing, considering the Array.includes(), Set.has() and DOMTokenList.contains() methods.

The ArrayList class aims to reuse as much of JavaScript’s Array as possible but pack it into a clean and consistent API that offers all methods under the collection instance itself, instead of passing the array along as parameter or extending the Array prototype which might break in the future. The only exception is the “L” property (for “list”) that is made available to all Arrays as kind of an extension property. It allows using ArrayList methods on an Array with minimal effort and clutter.

As a result, ArrayList is compact and easy to use, increasing the developer’s productivity and happiness. The minified and gzipped code is just 3 KiB. It is also fully covered by unit tests.

How?

Here are a few examples to show its usage and the results. First some list manipulation calls:

// Start with a plain Array let arr = ["Berlin", "Paris"]; // Insert at index 1 arr.L.insert(1, "Amsterdam"); → arr: ["Berlin", "Amsterdam", "Paris"] // Add many arr.L.addRange(["Vienna", "Rome", "Oslo", "Helsinki"]); → arr: ["Berlin", "Amsterdam", "Paris", "Vienna", "Rome", "Oslo", "Helsinki"] // Remove by predicate arr.L.removeAll(x => x.length > 6); → arr: ["Berlin", "Paris", "Vienna", "Rome", "Oslo"] // Replace by value, also shuffle in the same line arr.L.replace("Rome", "London").shuffle(); → arr: ["Vienna", "London", "Oslo", "Paris", "Berlin"] (or other order)

Then methods that return a new ArrayList and don’t affect the original array or list:

// Return sorted copy, first by length, then by name arr.L.orderBy(x => x.length, x => x) → ["Oslo", "Paris", "Berlin", "London", "Vienna"] // Skip 1 (“Vienna”), take next as long as they have the letter “L” arr.L.skip(1) .takeWhile(x => x.match(/[Ll]/)) → ["London", "Oslo"] // Return all except these two arr.L.except(["Vienna", "Paris"]) → ["London", "Oslo", "Berlin"] // Return all and these if not already there arr.L.union(["Vienna", "Madrid"]) → ["Vienna", "London", "Oslo", "Paris", "Berlin", "Madrid"]

Most of these methods are implemented independently from each other so they can also be copied into other applications and libraries individually. Most method implementations are also rather short. All methods have unit test cases for all possible combinations of inputs, also covering side effects.

Note:
As a general rule, all collections returned by ArrayList methods will be of the ArrayList type. All ArrayList methods that take collections as parameters will accept Array and ArrayList instances, some might also accept any iterable. The examples in this documentation are kept as simple as possible. The test cases include both types of parameters where possible.

Note:
Where the Array methods expect a parameter like endIndex, referring to the last index before which to stop an operation, the ArrayList methods usually expect a count parameter, referring to the number of processed items. This is usually more intuitive, easier to write and in line with the .NET APIs.

Where?

As a modern JavaScript library, this code is compatible with the following environments:

Earlier versions may work for a limited feature set. The vastly outdated and now abandoned Internet Explorer is explicitly incompatible with this code. Should you be stuck in the past for whatever reason, a transpiler like Babel and a few polyfills might help you out.

This library is released under the terms of the MIT licence. See the complete licence text in the code repository for details.

Documentation

This documentation lists all public members of the ArrayList class. The available parameters are listed for each method, describing which of them are optional or alternative in which combination. The description explains the behaviour and parameter requirements. The return value is shown after the arrow. A link to the Array class method is provided where there’s great similarity in their function.

A few examples further describe the usage and effect of a method. More comprehensive input and output of a method can be found in the separate test cases included in the source code.

Search

The members are categorised and can be searched (just type ahead). The search also uses aliases for many entries. Start the search text with an equals sign (=) to ignore aliases. Start the search text with the ^ sign to also only find names starting with the search term. Press Escape to reset the search.

Constructor

ArrayList

  • new ArrayList(array) → ArrayList
  • new ArrayList(iterable) → ArrayList
  • new ArrayList(number) → ArrayList

Creates a new ArrayList instance that contains the items included in the specified Array or Iterable. If an Array is specified, that Array is wrapped by the ArrayList instance and manipulations will also be seen in that Array and vice versa. If a Number is specified, the new array length is set.

Array.L

  • Array.L → ArrayList

The L property for Array instances provides access to the additional features implemented in ArrayList. This is the only addition to other prototypes made by this library. array.L is a shortcut for: new ArrayList(array)

let arr = [1, 2, 3]; arr.L.addRange([4, 5]); → arr: [1, 2, 3, 4, 5]

It can also be used to make use of ArrayList methods in a workflow that requires plain Arrays, together with the “array” property or toArray() method to get back the internal array.

let arr = [1, 2, 3, 4]; arr.L.take(3).reversed().array → [3, 2, 1] → arr: [1, 2, 3, 4]

See also: ArrayList.array, ArrayList.toArray()

Instance properties

array

  • array → Array

Gets the internal array of the ArrayList instance. This property cannot be written. The returned array is the actual object used by the ArrayList instance. It contains exactly the items of the collection. Any changes done to this array will also be reflected in the ArrayList instance.

This property is the inverse of the ArrayList constructor that takes an Array instance to wrap. It allows to switch from an Array to ArrayList (with the constructor or the “L” property added to the Array prototype) to use its manipulation methods and then switch back to Array for external use.

See also: ArrayList.toArray()

first

  • first → Any

Gets or sets the first item of the array. If there is no first item, undefined is returned.

This is an alternative to: ArrayList.array[0]

let arr = [1, 2, 3, 4]; arr.L.first → 1 arr.L.first = 9; → arr: [9, 2, 3, 4] arr = []; arr.L.first → undefined

last

  • last → Any

Gets or sets the last item of the array. If the array is empty, undefined is returned and setting the property throws an error.

This is an alternative to: ArrayList.array[ArrayList.length - 1] or ArrayList.get(-1)

let arr = [1, 2, 3, 4]; arr.L.last → 4 arr.L.last = 9; → arr: [1, 2, 3, 9] arr = []; arr.L.last → undefined

length

  • length → Number

Gets the number of items in the array. This property cannot be written.

This returns the same value as: ArrayList.array.length

let arr = [2, 4, 6, 8]; arr.L.length → 4

See also: Array.length

second

  • second → Any

Gets or sets the second item of the array. If there is no second item, undefined is returned.

This is an alternative to: ArrayList.array[1]

let arr = [1, 2, 3, 4]; arr.L.second → 2 arr.L.second = 9; → arr: [1, 9, 3, 4] arr = []; arr.L.second → undefined arr.L.second = 9; → arr: [<empty slot>, 9]

Item retrieval methods

These instance methods retrieve a single item from the array or a single aggregated value computed from the array.

aggregate

  • aggregate(reducer) → Any
  • aggregate(initialValue, reducer) → Any

Applies an accumulator function over the array. The reducer function is called with two arguments and returns a single value that combines both. Then the function is called with the previous return value and the next array item, until the last item. If the initialValue is unset and the array is empty, undefined is returned. If the initialValue is set, it is the first argument of the first call of the reducer function.

["correct", "horse", "battery", "staple"].L.aggregate((a, b) => a + b) → "correcthorsebatterystaple" [2, 3, 5, 7, 11].L.aggregate((a, b) => a + b) → 28 [2, 3, 5, 7, 11].L.aggregate(10, (a, b) => a + b) → 38 [].L.aggregate((a, b) => a + b) → undefined [].L.aggregate(10, (a, b) => a + b) → 10

See also: Array.reduce(), ArrayList.aggregateReversed()

aggregateReversed

  • aggregateReversed(reducer) → Any
  • aggregateReversed(initialValue, reducer) → Any

Applies an accumulator function over the array in reversed order. See the aggregate() method for more details.

["correct", "horse", "battery", "staple"].L.aggregate((a, b) => a + b) → "staplebatteryhorsecorrect"

See also: Array.reduceRight(), ArrayList.aggregate()

all

  • all(predicate) → Boolean
  • all(predicate, thisArg) → Boolean

Determines whether all items in the array satisfy a condition. The predicate function gets three arguments:

  1. The array item
  2. Its index in the array
  3. The entire array (the internal Array instance)

If thisArg is set, it is assigned to this when executing the predicate function. If the array is empty, true is returned. The parameter semantics is the same as the Array.every() method.

[1, 2, 3].L.all(x => x > 0) → true [-1, 0, 3].L.all(x => x > 0) → false [-1, -2, -3].L.all(x => x > 0) → false

See also: Array.every()

any

  • any() → Boolean
  • any(predicate) → Boolean
  • any(predicate, thisArg) → Boolean

Determines whether any item in the array satisfies a condition. The predicate function gets three arguments:

  1. The array item
  2. Its index in the array
  3. The entire array (the internal Array instance)

If no predicate is specified, the return value is true only if the array contains any items. If thisArg is set, it is assigned to this when executing the predicate function. If the array is empty, false is returned. The parameter semantics is the same as the Array.some() method.

[1, 2, 3].L.any(x => x > 0) → true [-1, 0, 3].L.any(x => x > 0) → true [-1, -2, -3].L.any(x => x > 0) → false [1, 2, 3].L.any() → true [].L.any() → false

See also: Array.some()

average

  • average() → Number
  • average(selector) → Number

Computes the average value of items in the array. The optional selector function is called for each item of the array and returns the value to use for the average computation. If the selector is omitted, the array must contain numbers only. If the array is empty, undefined is returned.

[1, 2, 3, 4].L.average() → 2.5 [{a: 1}, {a: 2}].L.average(x => x.a) → 1.5 [].L.average() → undefined

binarySearch

  • binarySearch(item) → Number
  • binarySearch(item, comparer) → Number

Searches the sorted array for an item using the comparer and returns the zero-based index of the item. If the item is not found, the return value is a negative number that is the bitwise complement (~) of the index of the next item that is larger than item or, if there is no larger item, the bitwise complement of the length property.

[1, 2, 5, 7].L.binarySearch(2) → 1 [1, 2, 5, 7].L.binarySearch(-2) → -1 (~0) [1, 2, 5, 7].L.binarySearch(4) → -3 (~2) [1, 2, 5, 7].L.binarySearch(10) → -5 (~4) [].L.binarySearch(2) → -1 (~0) [{a: 1}, {a: 2}, {a: 5}].L.binarySearch({a: 5}, (x, y) => x.a - y.a) → 2

contains

  • contains(item) → Boolean
  • contains(item, startIndex) → Boolean

Determines whether an item exists in the array. The parameter semantics is the same as the Array.includes() method.

["Berlin", "Paris", "London"].L.contains("London") → true ["Berlin", "Paris", "London"].L.contains("Vienna") → false ["Berlin", "Paris", "London"].L.contains("Berlin", 1) → false

See also: Array.includes()

count

  • count() → Number
  • count(predicate) → Number

Counts the items in the array that satisfy a condition. If no predicate is specified, the array length is returned.

["Berlin", "Paris", "London"].L.count() → 3 ["Berlin", "Paris", "London"].L.count(x => x.length === 6) → 2

equals

  • equals(other) → Boolean

Determines whether two arrays contain the same items in the same order. The values are compared with the === operator.

[1, 2, 3, 4].L.equals([1, 2, 3]) → false [1, 2, 3, 4].L.equals([1, 2, 4, 3]) → false [1, 2, 3, 4].L.equals([1, 2, 3, 4]) → true

See also: ArrayList.setEquals()

find

  • find(predicate) → Any
  • find(predicate, thisArg) → Any

Returns the first item in the array that satisfies a condition. If no values satisfy the condition, undefined is returned. The predicate function gets three arguments:

  1. The array item
  2. Its index in the array
  3. The entire array (the internal Array instance)

If thisArg is set, it is assigned to this when executing the predicate function. The parameter semantics is the same as the Array.find() method.

["Paris", "Berlin", "London", "Oslo"].L.find(x => x.length === 6) → "Berlin"

See also: Array.find()

findIndex

  • findIndex(predicate) → Number
  • findIndex(predicate, thisArg) → Number

Returns the index of the first item in the array that satisfies a condition. If no values satisfy the condition, the return value is -1. The predicate function gets three arguments:

  1. The array item
  2. Its index in the array
  3. The entire array (the internal Array instance)

If thisArg is set, it is assigned to this when executing the predicate function. The parameter semantics is the same as the Array.findIndex() method.

["Paris", "Berlin", "London", "Oslo"].L.findIndex(x => x.length === 6) → 1

See also: Array.findIndex(), ArrayList.find()

findLast

  • findLast(predicate) → Any
  • findLast(predicate, thisArg) → Any

Returns the last item in the array that satisfies a condition. If no values satisfy the condition, undefined is returned. The predicate function gets three arguments:

  1. The array item
  2. Its index in the array
  3. The entire array (the internal Array instance)

If thisArg is set, it is assigned to this when executing the predicate function. The parameter semantics is the same as the Array.find() method.

["Paris", "Berlin", "London", "Oslo"].L.findLast(x => x.length === 6) → "London"

findLastIndex

  • findLastIndex(predicate) → Number
  • findLastIndex(predicate, thisArg) → Number

Returns the index of the last item in the array that satisfies a condition. If no values satisfy the condition, the return value is -1. The predicate function gets three arguments:

  1. The array item
  2. Its index in the array
  3. The entire array (the internal Array instance)

If thisArg is set, it is assigned to this when executing the predicate function. The parameter semantics is the same as the Array.findIndex() method.

["Paris", "Berlin", "London", "Oslo"].L.findLastIndex(x => x.length === 6) → 2

See also: ArrayList.findLast()

get

  • get(index) → Any

Returns the item at the positive or negative index of the array. If the index is negative, it is counted from the end, i.e. -1 is the last, -2 the second-last item, etc. If the index is outside the range of the array, undefined is returned.

["Berlin", "Paris", "London", "Oslo"].L.get(0) → "Berlin" ["Berlin", "Paris", "London", "Oslo"].L.get(1) → "Paris" ["Berlin", "Paris", "London", "Oslo"].L.get(-2) → "London"

See also: Array[index], ArrayList.set()

indexOf

  • indexOf(item) → Number

Returns the first index of the item in the array. If the item does not exist in the array, the return value is -1.

["Berlin", "Paris", "London"].L.indexOf("London") → 2 ["Berlin", "Paris", "London"].L.indexOf("Rome") → -1

See also: Array.indexOf()

join

  • join() → String
  • join(separator) → String

Returns a string by concatenating all of the elements of the array, separated by commas or the specified separator string. If the array has only one item, then that item will be returned without using the separator. If the array is empty, an empty string is returned.

["Berlin", "Paris", "London"].L.join() → "Berlin,Paris,London" ["Berlin", "Paris", "London"].L.join(" – ") → "Berlin – Paris – London"

See also: Array.join()

lastIndexOf

  • lastIndexOf(item) → Number

Returns the last index of the item in the array. If the item does not exist, the return value is -1.

["Berlin", "Paris", "London", "Paris"].L.lastIndexOf("Paris") → 3 ["Berlin", "Paris", "London", "Paris"].L.lastIndexOf("Rome") → -1

See also: Array.lastIndexOf()

max

  • max() → Number
  • max(selector) → Number

Computes the maximum value of the items in the array. The optional selector function is called for each item of the array and returns the value to use for the maximum computation. If the selector is omitted, the array must contain numbers only. The selector must return numbers only. If the array is empty, undefined is returned.

[1, 2, 3, 4].L.max() → 4 [{a: 1}, {a: 2}].L.max(x => x.a) → 2 [].L.max() → undefined

maxBy

  • maxBy(selector) → Any

Returns the item in the array with the maximum value returned by the selector. The selector function is called for each item of the array and returns the value to use for the maximum test. If the array is empty, undefined is returned.

[{a: "a", x: 1}, {a: "b", x: 2}, {c: "", x: 3}].L.maxBy(i => i.x) → {c: "", x: 3} [].L.maxBy(i => i) → undefined

Added in v2.1.0

min

  • min() → Number
  • min(selector) → Number

Computes the minimum value of the items in the array. The optional selector function is called for each item of the array and returns the value to use for the minimum computation. If the selector is omitted, the array must contain numbers only. The selector must return numbers only. If the array is empty, undefined is returned.

[1, 2, 3, 4].L.min() → 1 [{a: 1}, {a: 2}].L.min(x => x.a) → 1 [].L.min() → undefined

minBy

  • minBy(selector) → Any

Returns the item in the array with the minimum value returned by the selector. The selector function is called for each item of the array and returns the value to use for the minimum test. If the array is empty, undefined is returned.

[{a: "a", x: 1}, {a: "b", x: 2}, {c: "", x: 3}].L.minBy(i => i.x) → {a: "a", x: 1} [].L.maxBy(i => i) → undefined

Added in v2.1.0

sum

  • sum() → Number
  • sum(selector) → Number

Computes the sum of the items in the array. The optional selector function is called for each item of the array and returns the value to use for the sum computation. If the selector is omitted, the array must contain numbers only. If the array is empty, undefined is returned.

[1, 2, 3, 4].L.sum() → 10 [{a: 1}, {a: 2}].L.sum(x => x.a) → 3 [].L.sum() → undefined

Manipulation methods

These instance methods alter the contents of the array. Most of these methods return the instance for chained calls, except the remove and replace methods.

add

  • add(item) → this

Adds an item to the end of the array.

let arr = [1, 2]; arr.L.add(3); → arr: [1, 2, 3]

See also: Array.push()

addRange

  • addRange(items) → this

Adds many items to the end of the array.

let arr = [1, 2]; arr.L.addRange([3, 4, 5]); → arr: [1, 2, 3, 4, 5]

See also: ArrayList.concat() (copying alternative)

clear

  • clear() → this

Removes all items from the array. This is equivalent of setting array.length = 0.

let arr = [1, 2]; arr.L.clear(); → arr: []

fill

  • fill(value) → this
  • fill(value, start) → this
  • fill(value, start, count) → this

Changes all elements in the array to a static value. The length of the array is not changed. If the array is empty, nothing is changed. If the start is negative, it is counted from the end, i.e. -1 is the last, -2 the second-last item, etc. If count is omitted, all items from the start index to the end of the array are changed. If count is negative, the items until (excluding) the count index from the end of the array are changed, i.e. -1 excludes the last, -2 excludes the 2 last items, etc.

let arr = [1, 2, 3]; arr.L.fill(9); → arr: [9, 9, 9] arr = [1, 2, 3, 4, 5]; arr.L.fill(9, 3); → arr: [1, 2, 3, 9, 9] arr = [1, 2, 3, 4, 5]; arr.L.fill(9, 2, 2); → arr: [1, 2, 9, 9, 5]

See also: Array.fill()

insert

  • insert(index, item) → this

Inserts an item into the array at the specified index. If the index is negative, it is counted from the end, i.e. -1 is the last, -2 the second-last item, etc. If index is greater than the array length, the item is added at the end of the array. If the negative index points to a position before the start of the array, the item is inserted at the beginning of the array.

let arr = [1, 2]; arr.L.insert(0, 3); → arr: [3, 1, 2] arr.L.insert(-1, 9); → arr: [3, 1, 9, 2]

insertRange

  • insertRange(index, items) → this

Inserts many items into the array at the specified index. If the index is negative, it is counted from the end, i.e. -1 is the last, -2 the second-last item, etc. If index is greater than the array length, the items are added at the end of the array. If the negative index points to a position before the start of the array, the item is inserted at the beginning of the array.

let arr = [1, 2]; arr.L.insert(1, [3, 4]); → arr: [1, 3, 4, 2]

remove

  • remove(item) → Boolean

Removes an item by value from the array. The return value is true if the item was found; otherwise, false.

let arr = [1, 2, 3, 4]; arr.L.remove(3); → arr: [1, 2, 4]

removeAll

  • removeAll(predicate) → ArrayList
  • removeAll(predicate, thisArg) → ArrayList

Removes and returns all items from the array that satisfy a condition. If no items were removed, the return valus is an empty array. The predicate function gets three arguments:

  1. The array item
  2. Its index in the array
  3. The entire array (the internal Array instance)

If thisArg is set, it is assigned to this when executing the predicate function.

const even = x => x % 2 === 0; let arr = [1, 2, 3, 4, 5]; arr.L.removeAll(even); → arr: [1, 3, 5]

removeAt

  • removeAt(index) → Any

Removes and returns an item by index from the array. If the index is negative, it is counted from the end, i.e. -1 is the last, -2 the second-last item, etc. If index is greater than the array length, nothing is removed and undefined is returned. If the negative index points to a position before the start of the array, the first item is removed and returned.

let arr = [1, 2, 3, 4]; arr.L.removeAt(0); → arr: [2, 3, 4] arr.L.removeAt(-1); → arr: [2, 3]

removeFirst

  • removeFirst() → Any

Removes and returns the first item from the array. If the array is empty, undefined is returned.

let arr = [1, 2, 3, 4]; arr.L.removeFirst(); → arr: [2, 3, 4]

See also: Array.shift(), ArrayList.skip() (copying alternative)

removeLast

  • removeLast() → Any

Removes and returns the last item from the array. If the array is empty, undefined is returned.

let arr = [1, 2, 3, 4]; arr.L.removeLast(); → arr: [1, 2, 3]

See also: Array.pop(), ArrayList.skipLast() (copying alternative)

removeRange

  • removeRange(items) → ArrayList
  • removeRange(start) → ArrayList
  • removeRange(start, count) → ArrayList

Removes and returns many items from the array, either by index and count or the specified items. If the start is negative, it is counted from the end, i.e. -1 is the last, -2 the second-last item, etc. If count is omitted, all items from the start index to the end of the array are removed. If count is negative, the items until (excluding) the count index from the end of the array are removed, i.e. -1 keeps the last, -2 keeps the 2 last items, etc. If no items were removed, the return valus is an empty array.

let arr = [1, 2, 3, 4, 5, 6, 7, 8]; arr.L.removeRange([2, 3]); → arr: [1, 4, 5, 6, 7, 8] arr.L.removeRange(1, 2); → arr: [1, 6, 7, 8] arr.L.removeRange(2); → arr: [1, 6]

replace

  • replace(oldItem, newItem) → Boolean

Replaces the first item by the value of oldItem in the array. The return value is true if the old item was found; otherwise, false.

let arr = [1, 2, 3, 4]; arr.L.replace(3, 9); → arr: [1, 2, 9, 4]

reverse

  • reverse() → this

Reverses the array in-place.

let arr = [1, 2, 3, 4]; arr.L.reverse(); → arr: [4, 3, 2, 1]

See also: Array.reverse(), ArrayList.reversed() (copying alternative)

set

  • set(index, value) → this

Sets the item at the positive or negative index of the array. If the index is negative, it is counted from the end, i.e. -1 is the last, -2 the second-last item, etc. If index is greater than the array length, empty slots will be created between the old last and the new item. If the negative index points to a position before the start of the array, the property representing the negative number is created but the set value is not part of the iterable items of the array. This behaviour is identical to setting arbitrary indexes of a plain Array.

let arr = [1, 2, 3, 4]; arr.L.set(0, 9); → arr: [9, 2, 3, 4] arr.L.set(-1, 8); → arr: [9, 2, 3, 8]

See also: Array[index], ArrayList.get()

shuffle

  • shuffle() → this

Shuffles the array using a Fisher-Yates algorithm.

let arr = [1, 2, 3, 4, 5, 6]; arr.L.shuffle(); → arr: [4, 6, 2, 3, 1, 5] (or other order)

sort

  • sort() → this
  • sort(comparer) → this

Sorts the array using string order or the comparer function.

let arr = ["plum", "strawberry", "apple", "peach", "carrot", "raspberry"]; arr.L.sort(); → arr: ["apple", "carrot", "peach", "plum", "raspberry", "strawberry"] arr = [1, 4, 30, 5, 222]; arr.L.sort(); → arr: [1, 222, 30, 4, 5] arr = [1, 4, 3, 5, 2]; arr.L.sort((a, b) => b - a); → arr: [5, 4, 3, 2, 1]

See also: Array.sort()

sortBy

  • sortBy(keySelector, …) → this

Sorts the array in ascending order according to a key. Secondary sorting is done by providing more key selector arguments. An argument of 1 or -1 sets the sort direction of the following keys ascending or descending, respectively.

The comparison is done with the < (less than) and > (greater than) operators. Two numbers are compared by their numeric value, two strings are compared lexically. nulls always follow after values, undefineds follow after nulls. Mixed-type comparisons have unpredictable results.

let arr = [ { id: 5, name: "apple"}, { id: 1, name: "raspberry"}, { id: 4, name: "peach"}, { id: 3, name: "carrot"}, { id: 2, name: "apple"} ]; arr.L.sortBy(x => x.id); → arr: [ → { id: 1, name: "raspberry"}, → { id: 2, name: "apple"}, → { id: 3, name: "carrot"}, → { id: 4, name: "peach"}, → { id: 5, name: "apple"} → ] arr.L.sortBy(x => x.name, x => x.id); → arr: [ → { id: 2, name: "apple"}, → { id: 5, name: "apple"}, → { id: 3, name: "carrot"}, → { id: 4, name: "peach"}, → { id: 1, name: "raspberry"} → ] arr.L.sortBy(x => x.name, -1, x => x.id); → arr: [ → { id: 5, name: "apple"}, → { id: 2, name: "apple"}, → { id: 3, name: "carrot"}, → { id: 4, name: "peach"}, → { id: 1, name: "raspberry"} → ]

See also: ArrayList.orderBy() (copying alternative)

sortByDescending

  • sortByDescending(keySelector, …) → this

Sorts the array in descending order according to a key. Secondary sorting is done by providing more key selector arguments. An argument of 1 or -1 sets the sort direction of the following keys ascending or descending, respectively.

The comparison is done with the < (less than) and > (greater than) operators. Two numbers are compared by their numeric value, two strings are compared lexically. nulls always follow after values, undefineds follow after nulls. Mixed-type comparisons have unpredictable results.

See the sortBy() method for an example. This method differs in that the initial sort order is descending instead of ascending. Both methods behave identically if the first argument is 1 or -1.

See also: ArrayList.orderByDescending() (copying alternative)

sortByUseLocale

  • sortByUseLocale(keySelector, …) → this

Sorts the array in ascending order according to a key, using locale string comparison. Secondary sorting is done by providing more key selector arguments. An argument of 1 or -1 sets the sort direction of the following keys ascending or descending, respectively.

The comparison is done with the localeCompare() method if both values are strings; otherwise, < (less than) and > (greater than) operators. Two numbers are compared by their numeric value, two strings are compared according to the current locale. nulls always follow after values, undefineds follow after nulls. Mixed-type comparisons have unpredictable results.

See the sortBy() method for an example. This method differs in the string comparison.

See also: ArrayList.orderByUseLocale() (copying alternative)

Added in v2.1.0

sortByDescendingUseLocale

  • sortByDescendingUseLocale(keySelector, …) → this

Sorts the array in descending order according to a key, using locale string comparison. Secondary sorting is done by providing more key selector arguments. An argument of 1 or -1 sets the sort direction of the following keys ascending or descending, respectively.

The comparison is done with the localeCompare() method if both values are strings; otherwise, < (less than) and > (greater than) operators. Two numbers are compared by their numeric value, two strings are compared according to the current locale. nulls always follow after values, undefineds follow after nulls. Mixed-type comparisons have unpredictable results.

See the sortBy() method for an example. This method differs in the string comparison and that the initial sort order is descending instead of ascending.

See also: ArrayList.orderByDescendingUseLocale() (copying alternative)

Added in v2.1.0

sortNumeric

  • sortNumeric() → this

Sorts the array using numerical order. The array must contain numbers only.

let arr = [1, 4, 30, 5, 222]; arr.L.sortNumeric(); → arr: [1, 4, 5, 30, 222]

Copy methods

These instance methods return multiple items from the array in a new collection and do not alter the contents of the instance.

Note:
Most of these methods return an ArrayList instance even though the example output shown looks like a plain Array for brevity. After all, JSON serialisation of ArrayList and Array have the same result.

Hint:
Copying the result items to a new array instance allocates additional memory. If the method is called on an ArrayList instance that is already a new collection, for example in multiple chained method calls, a manipulating alternative (where available) may in some cases provide better runtime or memory performance.

chunk

  • chunk(length) → ArrayList
  • chunk(length, pad) → ArrayList

Chunks the array into multiple arrays of a maximum length, with optional padding of the last shorter chunk. Each subarray is again an ArrayList instance. The result can be converted to a plain Array of Arrays with the toArray() method.

[1, 2, 3, 4, 5, 6].L.chunk(2) → [[1, 2], [3, 4], [5, 6]] [1, 2, 3, 4, 5].L.chunk(2) → [[1, 2], [3, 4], [5]] [1, 2, 3, 4, 5].L.chunk(2, "a") → [[1, 2], [3, 4], [5, "a"]]

concat

  • concat() → ArrayList
  • concat(array, …) → ArrayList

Concatenates the array with the other specified arrays. If no parameter is specified, this method behaves the same as the clone() method.

[1, 2, 3].L.concat() → [1, 2, 3] (copy of original array, with same items) [1, 2, 3].L.concat([4, 5]) → [1, 2, 3, 4, 5] [1, 2, 3].L.concat([4, 5], [6], [7]) → [1, 2, 3, 4, 5, 6, 7]

See also: Array.concat(), ArrayList.addRange() (manipulating alternative)

clone

  • clone() → ArrayList

Returns a new array with the items from the array.

[1, 2, 3].L.clone() → [1, 2, 3] (copy of original array, with same items)

See also: Array.concat()

cycle

  • cycle(count) → ArrayList

Returns a new array containing the items from the array, cycling until the target length has been reached. If the array is empty, an empty array is returned.

[1, 2, 3].L.cycle(2) → [1, 2] [1, 2, 3].L.cycle(8) → [1, 2, 3, 1, 2, 3, 1, 2] [].L.cycle(2) → []

flat

  • flat() → ArrayList
  • flat(depth) → ArrayList

Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth. If the depth is not set, it defaults to 1.

[1, [2], [3, [4, 5, [6, 7]]]].L.flat() → [1, 2, 3, [4, 5, [6, 7]]] [1, [2], [3, [4, 5, [6, 7]]]].L.flat(2) → [1, 2, 3, 4, 5, [6, 7]]

See also: Array.flat()

getRange

  • getRange(start) → ArrayList
  • getRange(start, count) → ArrayList

Returns items from the array. If the start is negative, it is counted from the end, i.e. -1 is the last, -2 the second-last item, etc. If count is omitted, all items from the start index to the end of the array are returned. If count is negative, the items until (excluding) the count index from the end of the array are returned, i.e. -1 excludes the last, -2 excludes the 2 last items, etc.

[1, 2, 3, 4, 5].L.getRange(3) → [4, 5] [1, 2, 3, 4, 5].L.getRange(1, 3) → [2, 3, 4]

See also: Array.slice()

groupBy

  • groupBy(keySelector) → Map
  • groupBy(keySelector, elementSelector) → Map

Groups the items of the array according to the key selector function and returns a new Map from each group key and an ArrayList of the items in the group. The order of the items in each returned group is the same as in the original array.

let arr = [ { key: 1, value: "a"}, { key: 1, value: "b"}, { key: 1, value: "c"}, { key: 2, value: "d"}, { key: 3, value: "e"} ]; arr.L.groupBy(x => x.key) → Map { → 1: [{ key: 1, value: "a"}, { key: 1, value: "b"}, { key: 1, value: "c"}], → 2: [{ key: 2, value: "d"}], → 3: [{ key: 3, value: "e"}] → } arr.L.groupBy(x => x.key, x => x.value) → Map { → 1: ["a", "b", "c"], → 2: ["d"], → 3: ["e"] → }

innerJoin

  • innerJoin(other) → ArrayList
  • innerJoin(other, constraint) → ArrayList
  • innerJoin(other, constraint, selector) → ArrayList

Correlates the elements of two arrays based on a join constraint. The constraint function is called with two arguments, one item from each array, and returns true if the combination matches. The result contains items that match in both arrays. This corresponds to an inner join in SQL. The order of the returned items is the same as the original array. This method has a runtime complexity of O(n²).

If no constraint function is specified, the result is a cross join, or cartesian product, of the length of this array multiplied by the length of the other array. If no selector is specified, Object.assign() is used to combine the properties of both matching items, where equally named properties of the other array overwrite properties of this array. To keep separate properties with the same name from both array items, a selector must be used to project the properties to different names.

let arr = [ { id: 1, b: "1" }, { id: 2, b: "2" }, { id: 3, b: "3" } ]; let other = [ { id2: 1, y: "11" }, { id2: 1, y: "12" }, { id2: 3, y: "33" }, { id2: 4, y: "44" } ]; arr.L.innerJoin(other, (left, right) => left.id === right.id2) → [ → { id: 1, b: "1", id2: 1, y: "11" }, → { id: 1, b: "1", id2: 1, y: "12" }, → { id: 3, b: "3", id2: 3, y: "33" } → ] arr.L.innerJoin(other, (left, right) => left.id === right.id2, (left, right) => ({ id: left.id, name: right.y })) → [ → { id: 1, name: "11" }, → { id: 1, name: "12" }, → { id: 3, name: "33" } → ]

leftJoin

  • leftJoin(other) → ArrayList
  • leftJoin(other, constraint) → ArrayList
  • leftJoin(other, constraint, selector) → ArrayList

Correlates the elements of two arrays based on a join constraint. The constraint function is called with two arguments, one item from each array, and returns true if the combination matches. The result contains all items from this array, and the matched items from the other array. This corresponds to a left outer join in SQL. The order of the returned items is the same as the original array. This method has a runtime complexity of O(n²).

If no constraint function is specified, the result is a cross join, or cartesian product, of the length of this array multiplied by the length of the other array. If no selector is specified, Object.assign() is used to combine the properties of both matching items, where equally named properties of the other array overwrite properties of this array. To keep separate properties with the same name from both array items, a selector must be used to project the properties to different names. If there was no match in the other array, the second argument to the selector function is null.

let arr = [ { id: 1, b: "1" }, { id: 2, b: "2" }, { id: 3, b: "3" } ]; let other = [ { id2: 1, y: "11" }, { id2: 1, y: "12" }, { id2: 3, y: "33" }, { id2: 4, y: "44" } ]; arr.L.leftJoin(other, (left, right) => left.id === right.id2) → [ → { id: 1, b: "1", id2: 1, y: "11" }, → { id: 1, b: "1", id2: 1, y: "12" }, → { id: 2, b: "2" }, → { id: 3, b: "3", id2: 3, y: "33" } → ] arr.L.leftJoin(other, (left, right) => left.id === right.id2, (left, right) => ({ id: left.id, name: right ? right.y : "none" })) → [ → { id: 1, name: "11" }, → { id: 1, name: "12" }, → { id: 2, name: "none" }, → { id: 3, name: "33" } → ]

orderBy

  • orderBy(keySelector, …) → ArrayList

Returns a copy of the array in ascending order according to a key. Secondary sorting is done by providing more key selector arguments. An argument of 1 or -1 sets the sort direction of the following keys ascending or descending, respectively.

The comparison is done with the < (less than) and > (greater than) operators. Two numbers are compared by their numeric value, two strings are compared lexically. nulls always follow after values, undefineds follow after nulls. Mixed-type comparisons have unpredictable results.

let arr = [ { id: 5, name: "apple"}, { id: 1, name: "raspberry"}, { id: 4, name: "peach"}, { id: 3, name: "carrot"}, { id: 2, name: "apple"} ]; arr.L.orderBy(x => x.id) → [ → { id: 1, name: "raspberry"}, → { id: 2, name: "apple"}, → { id: 3, name: "carrot"}, → { id: 4, name: "peach"}, → { id: 5, name: "apple"} → ] arr.L.orderBy(x => x.name, x => x.id) → [ → { id: 2, name: "apple"}, → { id: 5, name: "apple"}, → { id: 3, name: "carrot"}, → { id: 4, name: "peach"}, → { id: 1, name: "raspberry"} → ] arr.L.orderBy(x => x.name, -1, x => x.id) → [ → { id: 5, name: "apple"}, → { id: 2, name: "apple"}, → { id: 3, name: "carrot"}, → { id: 4, name: "peach"}, → { id: 1, name: "raspberry"} → ]

See also: ArrayList.sortBy() (manipulating alternative)

orderByDescending

  • orderByDescending(keySelector, …) → ArrayList

Returns a copy of the array in descending order according to a key. Secondary sorting is done by providing more key selector arguments. An argument of 1 or -1 sets the sort direction of the following keys ascending or descending, respectively.

The comparison is done with the < (less than) and > (greater than) operators. Two numbers are compared by their numeric value, two strings are compared lexically. nulls always follow after values, undefineds follow after nulls. Mixed-type comparisons have unpredictable results.

See the orderBy() method for an example. This method differs in that the initial sort order is descending instead of ascending. Both methods behave identically if the first argument is 1 or -1.

See also: ArrayList.sortByDescending() (manipulating alternative)

orderByUseLocale

  • orderByUseLocale(keySelector, …) → ArrayList

Returns a copy of the array in ascending order according to a key, using locale string comparison. Secondary sorting is done by providing more key selector arguments. An argument of 1 or -1 sets the sort direction of the following keys ascending or descending, respectively.

The comparison is done with the localeCompare() method if both values are strings; otherwise, < (less than) and > (greater than) operators. Two numbers are compared by their numeric value, two strings are compared according to the current locale. nulls always follow after values, undefineds follow after nulls. Mixed-type comparisons have unpredictable results.

See the orderBy() method for an example. This method differs in the string comparison.

See also: ArrayList.sortByUseLocale() (manipulating alternative)

Added in v2.1.0

orderByDescendingUseLocale

  • orderByDescendingUseLocale(keySelector, …) → ArrayList

Returns a copy of the array in descending order according to a key, using locale string comparison. Secondary sorting is done by providing more key selector arguments. An argument of 1 or -1 sets the sort direction of the following keys ascending or descending, respectively.

The comparison is done with the localeCompare() method if both values are strings; otherwise, < (less than) and > (greater than) operators. Two numbers are compared by their numeric value, two strings are compared according to the current locale. nulls always follow after values, undefineds follow after nulls. Mixed-type comparisons have unpredictable results.

See the orderBy() method for an example. This method differs in the string comparison and that the initial sort order is descending instead of ascending.

See also: ArrayList.sortByDescendingUseLocale() (manipulating alternative)

Added in v2.1.0

outerJoin

  • outerJoin(other) → ArrayList
  • outerJoin(other, constraint) → ArrayList
  • outerJoin(other, constraint, selector) → ArrayList

Correlates the elements of two arrays based on a join constraint. The constraint function is called with two arguments, one item from each array, and returns true if the combination matches. The result contains all items when there is a match in either this or the other array. This corresponds to a full outer join in SQL. The order of the returned items is the same as the original array, followed by the new items from the other array. This method has a runtime complexity of O(2n²).

If no constraint function is specified, the result is a cross join, or cartesian product, of the length of this array multiplied by the length of the other array. If no selector is specified, Object.assign() is used to combine the properties of both matching items, where equally named properties of the other array overwrite properties of this array. To keep separate properties with the same name from both array items, a selector must be used to project the properties to different names. If there was no match in this or the other array, one of the arguments to the selector function is null.

let arr = [ { id: 1, b: "1" }, { id: 2, b: "2" }, { id: 3, b: "3" } ]; let other = [ { id2: 1, y: "11" }, { id2: 1, y: "12" }, { id2: 3, y: "33" }, { id2: 4, y: "44" } ]; arr.L.outerJoin(other, (left, right) => left.id === right.id2) → [ → { id: 1, b: "1", id2: 1, y: "11" }, → { id: 1, b: "1", id2: 1, y: "12" }, → { id: 2, b: "2" }, → { id: 3, b: "3", id2: 3, y: "33" }, → { id2: 4, y: "44" } → ] arr.L.outerJoin(other, (left, right) => left.id === right.id2, (left, right) => ({ id: left ? left.id : right.id2, name: right ? right.y : "none" })) → [ → { id: 1, name: "11" }, → { id: 1, name: "12" }, → { id: 2, name: "none" }, → { id: 3, name: "33" }, → { id: 4, name: "44" } → ]

rearrange

  • rearrange(mapper) → ArrayList

Returns a copy of the array with the items rearranged by a mapping function that maps the source index to the target index. The items are rearranged in their order in the array. If the mapping function returns a target index twice, the last assigned value will overwrite previous values at that index.

const mapper = index => (index + 2) % 6; [1, 2, 3, 4, 5, 6].L.rearrange(mapper) → [5, 6, 1, 2, 3, 4]

repeat

  • repeat(count) → ArrayList

Returns a copy of the array repeated multiple times. If count is 0, the returned array is empty.

[1, 2, 3].L.repeat(3) → [1, 2, 3, 1, 2, 3, 1, 2, 3]

reversed

  • reversed() → ArrayList

Returns a reversed copy of the array.

[1, 2, 3, 4].L.reversed() → [4, 3, 2, 1]

See also: ArrayList.reverse() (manipulating alternative)

select

  • select(selector) → ArrayList
  • select(selector, thisArg) → ArrayList

Projects each item in the array into a new form by calling the selector function for each item. The returned array contains as many items as the array, with each return value of the selector function called with the original item as parameter. If thisArg is set, it is assigned to this when executing the selector function. The parameter semantics is the same as the Array.map() method.

[1, 2, 3, 4].L.select(x => x + 10) → [11, 12, 13, 14] let arr = [ { key: 1, value: "a" }, { key: 1, value: "b" }, { key: 1, value: "c" }, { key: 2, value: "d" }, { key: 3, value: "e" } ]; arr.L.select(x => x.value) → ["a", "b", "c", "d", "e"]

See also: Array.map()

selectManyRecursive

  • selectManyRecursive(childrenSelector) → ArrayList

Recursively collects all items from the array and their children into a flat array. The returned array contains as many items as the array and all child items that can be found with the selector function. The childrenSelector function is called for each item with the item as parameter. It should return an array of all children of the item (can be empty), or a falsy value if there are no children.

let arr = [ { name: "a" }, { name: "b", children: [ { name: "b1" } ] }, { name: "c", children: [ { name: "c1" }, { name: "c2", children: [ { name: "c2a" } ] } ] }, { name: "d" } ]; arr.L.selectManyRecursive(x => x.children) .select(x => x.name) // for result brevity → ["a", "b", "b1", "c", "c1", "c2", "c2a", "d"]

skip

  • skip(count) → ArrayList

Returns a copy of the array without the first items.

[1, 2, 3, 4, 5, 6].L.skip(2) → [3, 4, 5, 6]

See also: Array.slice(), ArrayList.removeFirst() (manipulating alternative)

skipLast

  • skipLast(count) → ArrayList

Returns a copy of the array without the last items.

[1, 2, 3, 4, 5, 6].L.skipLast(2) → [1, 2, 3, 4]

See also: Array.slice(), ArrayList.removeLast() (manipulating alternative)

skipWhile

  • skipWhile(predicate) → ArrayList

Returns a copy of the array without the first items that satisfy a condition. As soon as an item does not satisfy the condition, that and all subsequent items until the end of the array are returned, satisfying the condition or not.

const even = x => x % 2 === 0; [2, 4, 6, 7, 8, 9].L.skipWhile(even) → [7, 8, 9]

take

  • take(count) → ArrayList

Returns the first items of the array.

[1, 2, 3, 4, 5, 6].L.take(2) → [1, 2]

See also: Array.slice()

takeAfter

  • takeAfter(item) → ArrayList

Returns all items in the array that occur after the specified item, not including the item itself.

["a", "b", "c", "d", "e"].L.takeAfter("c") → ["d", "e"]

takeBefore

  • takeBefore(item) → ArrayList

Returns all items in the array that occur before the specified item, not including the item itself.

["a", "b", "c", "d", "e"].L.takeBefore("c") → ["a", "b"]

takeEvery

  • takeEvery(step) → ArrayList
  • takeEvery(step, start) → ArrayList
  • takeEvery(step, start, count) → ArrayList

Returns every nth item of the array. If start is omitted, the first returned item is the first item of the array. The count defines how many items will be returned (if available), not how many items from the array will be considered.

[1, 2, 3, 4, 5, 6, 7, 8].L.takeEvery(2) → [1, 3, 5, 7] [1, 2, 3, 4, 5, 6, 7, 8].L.takeEvery(2, 1) → [2, 4, 6, 8] [1, 2, 3, 4, 5, 6, 7, 8].L.takeEvery(2, 1, 3) → [2, 4, 6]

takeLast

  • takeLast(count) → ArrayList

Returns the last items of the array.

[1, 2, 3, 4, 5, 6].L.takeLast(2) → [5, 6]

See also: Array.slice()

takeWhile

  • takeWhile(predicate) → ArrayList

Returns the first items of the array that satisfy a condition. As soon as an item does not satisfy the condition, no further items of the array are returned, satisfying the condition or not.

const even = x => x % 2 === 0; [2, 4, 6, 7, 8, 9].L.takeWhile(even) → [2, 4, 6]

toArray

  • toArray() → Array

Returns a plain Array of the items of the array, also converting all nested ArrayLists into Arrays. The returned array is a new instance that contains the items from the internal array. Any changes done to this array will not affect the ArrayList instance.

See also: ArrayList.array

toMap

  • toMap() → Map
  • toMap(keySelector) → Map
  • toMap(keyName) → Map
  • toMap(keySelector, valueSelector) → Map
  • toMap(keyName, valueSelector) → Map
  • toMap(keySelector, valueName) → Map
  • toMap(keyName, valueName) → Map

Returns a Map of the items of the array. The map key is determined by calling the keySelector function. The corresponding value is determined by calling the valueSelector function. The items are copied in their order in the array. If the key function returns a key twice, the last assigned value will overwrite previous values for that key.

If no keySelector is provided, the source array must contain arrays with exactly 2 items each, as for the Map constructor. The first of each array items is then used as key and the second item is the corresponding value.

If no valueSelector is provided, each source array item is used as the value.

Both the keySelector and valueSelector functions get three arguments:

  1. The array item
  2. Its index in the array
  3. The entire array (the internal Array instance)

If keySelector or valueSelector is a string instead of a function, it specifies the name of the property to read from each item object.

See the toObject() method for examples.

See also: ArrayList.toObject()

toObject

  • toObject() → Object
  • toObject(keySelector) → Object
  • toObject(keyName) → Object
  • toObject(keySelector, valueSelector) → Object
  • toObject(keyName, valueSelector) → Object
  • toObject(keySelector, valueName) → Object
  • toObject(keyName, valueName) → Object

Returns an Object of the items of the array. The object key is determined by calling the keySelector function which must return a string value suitable for a JavaScript object property name. The corresponding value is determined by calling the valueSelector function. The items are copied in their order in the array. If the key function returns a key twice, the last assigned value will overwrite previous values for that key.

If no keySelector is provided, the source array must contain arrays with exactly 2 items each, as for Object.fromEntries(). The first of each array items is then used as key and the second item is the corresponding value.

If no valueSelector is provided, each source array item is used as the value.

Both the keySelector and valueSelector functions get three arguments:

  1. The array item
  2. Its index in the array
  3. The entire array (the internal Array instance)

If keySelector or valueSelector is a string instead of a function, it specifies the name of the property to read from each item object.

// Convert [key, value] items [["a", 1], ["b", 2], ["c", 3]].L.toObject() → { "a": 1, "b": 2, "c": 3 } // Use keySelector [1, 2, 3].L.toObject(item => -item) → { "-1": 1, "-2": 2, "-3": 3 } // Use index-based keySelector [1, 2, 3].L.toObject((item, index) => index) → { "0": 1, "1": 2, "2": 3 } // Use keySelector and valueSelector let data = [ { key: "a", value: 1 }, { key: "b", value: 2 }, { key: "c", value: 3 } ]; data.L.toObject(item => item.key, item => item.value) → { "a": 1, "b": 2, "c": 3 } // Use keySelector and valueSelector as strings data.L.toObject("key", "value") → { "a": 1, "b": 2, "c": 3 }

The inverse operation of the last example would be this:

let data = { "a": 1, "b": 2, "c": 3 }; Object.entries(data).map(e => ({ key: e[0], value: e[1] })) → [ → { key: "a", value: 1 }, → { key: "b", value: 2 }, → { key: "c", value: 3 } → ]

See also: ArrayList.toMap()

transpose

  • transpose() → ArrayList
  • transpose(chunkSize) → ArrayList

Returns an array of arrays where each array contains the first/second/etc. values from each of the current arrays. It transposes a data table or matrix made of arrays of arrays of the values, also called zip/unzip. Each subarray is again an ArrayList instance. The result can be converted to a plain Array of Arrays with the toArray() method.

out ↓
in → a1 a2 a3
b1 b2 b3
[["a1", "a2", "a3"], ["b1", "b2", "b3"]].L.transpose() → [["a1", "b1"], ["a2", "b2"], ["a3", "b3"]]

A single array can be converted for this method with the chunk() method. The result can be converted to a single array with the flat() method.

["a1", "a2", "a3", "b1", "b2", "b3"].L.chunk(3).transpose().flat() → ["a1", "b1", "a2", "b2", "a3", "b3"]

If the instance only contains a flat array, i.e. not an array of arrays, the method transposes it as a flat array directly. Only in this case, the chunkSize is required. The returned array will then also be flat.

["a1", "a2", "a3", "b1", "b2", "b3"].L.transpose(3) → ["a1", "b1", "a2", "b2", "a3", "b3"]

where

  • where(predicate) → ArrayList
  • where(predicate, thisArg) → ArrayList

Returns all items from the array that satisfy a condition. Items that do not satisfy the condition are skipped in the returned array. The order of the returned items is the same as the original array. The predicate function gets three arguments:

  1. The array item
  2. Its index in the array
  3. The entire array (the internal Array instance)

If thisArg is set, it is assigned to this when executing the predicate function. The parameter semantics is the same as the Array.filter() method.

const even = x => x % 2 === 0; [1, 2, 3, 4, 5, 6].L.where(even) → [2, 4, 6]

See also: Array.filter()

Set methods

These instance methods provide set operations on the array. Most of these methods should be available in the built-in Set type, but unfortunately are not.

distinct

  • distinct() → ArrayList

Returns a new array with the items from the array, without duplicates. The order of the returned items is the same as the original array.

[1, 5, 3, 2, 5, 3, 3, 4].L.distinct() → [1, 5, 3, 2, 4]

See also: new Set()

except

  • except(other) → ArrayList

Returns a new array with the unique items from the array, without (“minus”) all items from the other array, also called set difference. The order of the returned items is the same as the original array.

[1, 2, 3, 4, 5, 6].L.except([1, 4, 5]) → [2, 3, 6]

intersect

  • intersect(other) → ArrayList

Returns a new array with the unique items that exist in both the array and the other array. This corresponds to the boolean operator AND. The order of the returned items is the same as the original array.

[1, 2, 3, 4, 5, 6].L.intersect([1, 4, 5, 8, 9]) → [1, 4, 5]

isSubsetOf

  • isSubsetOf(other) → Boolean

Determines whether the array is a subset of the other array. If both arrays contain the same distinct items, the return value is true.

[1, 2, 3].L.isSubsetOf([1, 2, 3, 4, 5]) → true [1, 2, 3].L.isSubsetOf([1, 2, 3]) → true [1, 2, 3].L.isSubsetOf([1, 2]) → false [1, 2, 3].L.isSubsetOf([5, 6]) → false [1, 2, 3].L.isSubsetOf([2, 4, 1, 5, 3]) → true

isSupersetOf

  • isSupersetOf(other) → Boolean

Determines whether the array is a superset of the other array. If both arrays contain the same distinct items, the return value is true.

[1, 2, 3].L.isSupersetOf([1, 2, 3, 4, 5]) → false [1, 2, 3].L.isSupersetOf([1, 2, 3]) → true [1, 2, 3].L.isSupersetOf([1, 2]) → true [1, 2, 3].L.isSupersetOf([5, 6]) → false [1, 2, 3, 4, 5].L.isSupersetOf([2, 1, 3]) → true

setEquals

  • setEquals(other) → Boolean

Determines whether two arrays contain the same unique items but not necessarily in the same order (or quantity). Items are compared with Set.has().

[1, 2, 3].L.setEquals([1, 2, 3, 4, 5]) → false [1, 2, 3].L.setEquals([1, 2, 3]) → true [1, 2, 3].L.setEquals([1, 2]) → false [1, 2, 3].L.setEquals([2, 1, 3]) → true [1, 2, 3].L.setEquals([1, 2, 3, 3, 3]) → true

See also: ArrayList.equals()

symmetricDifference

  • symmetricDifference(other) → ArrayList

Returns a new array with the unique items that exist in either the array or the other array but not in both (called symmetric difference). This corresponds to the boolean operator XOR (exclusive OR). The order of the returned items is the same as the original array, followed by the new items from the other array.

[1, 2, 3, 4].L.symmetricDifference([3, 4, 5, 6]) → [1, 2, 5, 6]

union

  • union(other) → ArrayList

Returns a new array with the unique items from the array and also from the other array. This corresponds to the boolean operator OR. The order of the returned items is the same as the original array, followed by the new items from the other array.

[1, 2, 3, 4].L.union([3, 4, 5, 6]) → [1, 2, 3, 4, 5, 6]

Void methods

These instance methods do not return items from the array and do not alter the contents of the instance.

forEach

  • forEach(action) → this
  • forEach(action, thisArg) → this

Calls a function once for each item in the array. The callback function gets three arguments:

  1. The array item
  2. Its index in the array
  3. The entire array (the internal Array instance)

If thisArg is set, it is assigned to this when executing the callback function. The parameter semantics is the same as the Array.forEach() method.

["a", "b", "c"].L.forEach(x => console.log(x)); → a → b → c ["a", "b", "c"].L.forEach(x => console.log(x, i)); → a 0 → b 1 → c 2

See also: Array.forEach()

Infrastructure methods

toJSON

  • toJSON() → Array

Returns the internal Array so that an ArrayList instance can be serialised to JSON just like a regular Array. Be aware that the deserialised object will be an Array, not an ArrayList, because JSON cannot maintain the object type.

See also: JSON.stringify()

toString

  • toString() → String

Returns the result of the toString() method on the internal Array.

See also: Array.toString()

Symbol.iterator

  • [Symbol.iterator] → Function

Returns the iterator function of the ArrayList instance.

let list = [1, 2, 3].L.reversed(); for (let x of list) { console.log(x); } → 3 → 2 → 1

Static methods

version

  • ArrayList.version → String

Returns the version identifier string of the ArrayList library.

ArrayList.version → "1.0.0"

range

  • ArrayList.range(start, count) → ArrayList
  • ArrayList.range(start, count, step) → ArrayList

Creates an array that contains integer numbers from the start value, with the specified step or 1. The step can be any integer (positive or negative) other than 0.

ArrayList.range(2, 5) → [2, 3, 4, 5, 6] ArrayList.range(2, 5, 10) → [2, 12, 22, 32, 42] ArrayList.range(10, 3, -1) → [10, 9, 8]