Array Methods
Path:
/src/mod/array.coffee
compiled to/lib/mod/array.js
last()
Get the last element.
Example:
CoffeeScript Code util = require 'alinex-util'
test = [ 1,2,3,4,5 ]
result = util.array.last test
This results to:
CoffeeScript Code result = 5
Usage:
last(array, back)
- Parameter
-
array
-Array
to read fromback
-Integer
offset character position from the end to look for
- Return
- last element value
unique()
Remove duplicate entries from array.
Example:
CoffeeScript Code util = require 'alinex-util'
test = [ 1,2,2,3,4,1,5 ]
result = util.array.unique test
This results to:
CoffeeScript Code result = [1,2,3,4,5]
Usage:
unique(array)
- Parameter
-
array
-Array
to to be checked
- Return
Array
new array with duplicates removed
sortBy()
Sort array of objects.
Example:
CoffeeScript Code util = require 'alinex-util'
test = [
{first: 'Johann Sebastion', last: 'Bach'}
{first: 'Wolfgang Amadeus', last: 'Mozart'}
{first: 'Joseph', last: 'Haydn'}
{first: 'Richard', last: 'Wagner'}
{first: 'Antonio', last: 'Vivaldi'}
{first: 'Michael', last: 'Haydn'}
{first: 'Franz', last: 'Schubert'}
]
# sort by last name ascending and first name descending
result = util.array.sortBy test, 'last', '-first'
This results to:
CoffeeScript Code result = [
{first: 'Johann Sebastion', last: 'Bach'}
{first: 'Michael', last: 'Haydn'}
{first: 'Joseph', last: 'Haydn'}
{first: 'Wolfgang Amadeus', last: 'Mozart'}
{first: 'Franz', last: 'Schubert'}
{first: 'Antonio', last: 'Vivaldi'}
{first: 'Richard', last: 'Wagner'}
]
Like displayed above you may give one or multiple field names to sort by the earlier has precedence. If field name starts with ‘-’ sign it will sort in descending order.
Usage:
sortBy(array, sort...)
- Parameter
-
array
-Array<Object>
to to be checkedsort...
-String
sort column name (if prepended with ‘-’ it will sort in descending order)
- Return
Array<Object>
new array in sorted order- Throws
-
Error
Missing sort column name.
shuffle()
Shuffle elements. But this only works if the array has more than two elements within else it will be kept unchanged.
Example:
CoffeeScript Code util = require 'alinex-util'
util.array.shuffle [1..9]
# => [ 3, 1, 5, 6, 4, 8, 2, 9, 7 ]
Usage:
shuffle(array)
- Parameter
-
array
-Array
to to be shuffled
- Return
Array
the same array