JAVASCRIPT
Array Utilities
All samples are using Ink.requireModules
, please read how to use it at Ink.requireModules section
Function name | Description |
---|---|
.convert(arr) | Converts an array-like object to an array |
.each([forEachArguments]) | Alias for backwards compatibility. See forEach |
.filter(array, test, [context]) | Filters an array based on a truth test. |
.forEach(array, callback, context) | Runs a function through each of the elements of an array. |
.forEachObj(obj, callback, [context]) | Like forEach, but for objects. |
.groupBy(arr, [options]) | Finds similar objects in an array and groups them together into subarrays for you. Groups have 1 or more item each. |
.inArray(value, arr) | Checks if a value exists in array |
.insert(arr, idx, value) | Inserts a value on a specified index |
.intersect(arr1, arr2) | Compares the values of two arrays and return the matches |
.isArray(testedObject) | Checks if a value is an array |
.keyValue(value, arr, [first]) | Gets the indexes of a value in an array |
.keys(obj) | Object.keys replacement. Returns a list of an object's own properties. |
.map(array, mapFn, [context]) | Runs a function for each item in the array. |
.range(start, stop, [step]) | Simulates python's range(start, stop, step) function. |
.reduce(array, callback, initial) | Replacement for Array.prototype.reduce. |
.remove(arr, from, rLen) | Removes a range of values from the array |
.shuffle(arr) | Shuffles an array. |
.some(arr, cb, context) | Checks if some element in the array passes a truth test |
.sortMulti(arr, key) | Sorts an array of objects by an object property |
.unique(arr) | Removes duplicated values in an array. |
Converts an array-like object to an array
arr
Array to be convertedConvert arguments
to an array.
Code
Ink.requireModules(['Ink.Util.Array_1'], function(InkArray) {
(function(a, b) {
var args = InkArray.convert(arguments);
Ink.log(args);
})('foo', 'bar');
});
Convert the result of querySelectorAll
to an array.
Code
Ink.requireModules(['Ink.Util.Array_1'], function(InkArray) {
var elements = document.querySelectorAll('.questions li');
// elements is now a NodeList.
// This is not convenient because NodeLists don't have much methods.
elements = InkArray.convert(elements);
// Now it's a real array
var last = elements.pop();
});
Since this returns a copy of the array, extra methods and other properties will be lost!
Code
Ink.requireModules(['Ink.Util.Array_1'], function(InkArray) {
var myArray = ['value_0', 'value_1'];
myArray.method = function() { };
myArray.prop = 'foobar';
Ink.log(typeof myArray.method); // function
var arr = InkArray.convert(myArray);
Ink.log(arr);
// ['value_0', 'value_1']
Ink.log(typeof arr.method); // undefined
});
Alias for backwards compatibility. See forEach
forEachArguments
(see forEach)Filters an array based on a truth test.
This method runs a test function on all the array values and returns a new array with all the values that pass the test.
array
The array to filtertest
A test function taking `(item, index, array)`context
Object to be `this` in the test function.Code
Ink.requireModules(['Ink.Util.Array_1'], function(InkArray) {
var testArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var oddArray = InkArray.filter(testArray, function(item) {
return ((item % 2) === 0);
});
Ink.log(oddArray);
// [2, 4, 6, 8, 10]
});
Runs a function through each of the elements of an array.
Uses Array.prototype.forEach if available.
array
The array to be cycled/iteratedcallback
The function receives as arguments the value, index and array.context
The value of `this` inside the `callback` you passed.Code
Ink.requireModules(['Ink.Util.Array_1'], function(InkArray) {
var testArray = [ 'value1', 'value2', 'value3', 'value2' ];
InkArray.forEach(testArray, function(value, index, arr) {
Ink.log( 'The value is: ' + value + ' | The index is: ' + index );
});
// The value is: value1 | The index is: 0
// The value is: value2 | The index is: 1
// The value is: value3 | The index is: 2
// The value is: value2 | The index is: 3
});
Like forEach, but for objects.
Calls callback
with (value, key, entireObject)
once for each key-value pair in obj
obj
Input objectcallback
Iteration callback, called once for each key/value pair in the object. `function (value, key, all) { this === context }`context
Set what the context (`this`) in the function will be.Iterate over a simple object
Code
Ink.requireModules(['Ink.Util.Array_1'], function(InkArray) {
var people = {
'Amy': '+351 234 564',
'John': '+351 444 444'
};
// List the people in our database.
InkArray.forEachObj(people, function(tel, name) {
console.log(name + ': ' + tel);
});
});
Finds similar objects in an array and groups them together into subarrays for you. Groups have 1 or more item each.
arr
The input array.options
Options object, containing:options.adjacentGroups
Set to `true` to mimick the python `groupby` function and only group adjacent things. For example, `'AABAA'` becomes `[['A', 'A'], ['B'], ['A', 'A']]` instead of `{ 'A': ['A', 'A', 'A', 'A'], 'B': ['B'] }`options.key
A function which computes the group key by which the items are grouped. Alternatively, you can pass a string and groupBy will pluck it out of the object and use that as a key.options.pairs
Set to `true` if you want to output an array of `[key, [group...]]` pairs instead of an array of groups.Example
InkArray.groupBy([1, 1, 2, 2, 3, 1]) // -> [ [1, 1, 1], [2, 2], [3] ]
InkArray.groupBy([1.1, 1.2, 2.1], { key: Math.floor }) // -> [ [1.1, 1.2], [2.1] ]
InkArray.groupBy([1.1, 1.2, 2.1], { key: Math.floor, pairs: true }) // -> [ [1, [1.1, 1.2]], [2, [2.1]] ]
InkArray.groupBy([1.1, 1.2, 2.1], { key: Math.floor, pairs: true }) // -> [ [1, [1.1, 1.2]], [2, [2.1]] ]
InkArray.groupBy([
{ year: 2000, month: 1 },
{ year: 2000, month: 2 },
{ year: 2001, month: 4 }
], { key: 'year' }) // -> [ [ { year: 2000, month: 1 }, { year: 2000, month: 2} ], [ { year: 2001, month: 2 } ] ]
Checks if a value exists in array
value
Value to checkarr
Array to search inCode
Ink.requireModules(['Ink.Util.Array_1'], function(InkArray) {
var testArray = [ 'value1', 'value2', 'value3', 'value2' ];
var isInArray;
isInArray = InkArray.inArray('value3', testArray);
Ink.log(isInArray); // true
isInArray = InkArray.inArray('foo', testArray);
Ink.log(isInArray); // false
});
Inserts a value on a specified index
arr
Array where the value will be insertedidx
Index of the array where the value should be insertedvalue
Value to be insertedCode
Ink.requireModules(['Ink.Util.Array_1'], function(InkArray) {
var testArray = [ 'value1', 'value2' ];
InkArray.insert(testArray, 1, 'value3');
Ink.log(testArray);
// ["value1", "value3", "value2"]
});
Compares the values of two arrays and return the matches
arr1
First arrayarr2
Second arrayCode
Ink.requireModules(['Ink.Util.Array_1'], function(InkArray) {
var testArray1 = [ 'value1', 'value2', 'value3' ];
var testArray2 = [ 'value2', 'value3', 'value4', 'value5', 'value6' ];
var matches = InkArray.intersect(testArray1, testArray2);
Ink.log(matches);
// ["value2", "value3"]
});
Checks if a value is an array
testedObject
The object we want to checkGets the indexes of a value in an array
value
Value to search for.arr
Array to run the search in.first
Flag to stop the search at the first match. It also returns an index number instead of an array of indexes.Code
Ink.requireModules(['Ink.Util.Array_1'], function(InkArray) {
var testArray = [ 'value1', 'value2', 'value3', 'value2' ];
var keyFound = InkArray.keyValue('value2', testArray, true);
Ink.log(keyFound);
// 1
var arrayKeyFound = InkArray.keyValue('value2', testArray);
Ink.log(arrayKeyFound);
// [1, 3]
var found = InkArray.keyValue('foobar', testArray, true);
Ink.log(found);
// false
});
Object.keys replacement. Returns a list of an object's own properties.
If Object.keys is available, just calls it.
obj
Object with the properties.Runs a function for each item in the array.
Uses Array.prototype.map if available.
That function will receive each item as an argument and its return value will change the corresponding array item.
array
The array to map overmapFn
The map function. Will take `(item, index, array)` as arguments and the `this` value will be the `context` argument you pass to this function.context
Object to be `this` in the map function.Code
Ink.requireModules(['Ink.Util.Array_1'], function(InkArray) {
var testArray = [1, 2, 3, 4];
var result = InkArray.map(testArray, function(item, index, arr) {
return item + 1;
});
Ink.log(result);
// [2, 3, 4, 5]
});
Code
Ink.requireModules(['Ink.Util.Array_1'], function(InkArray) {
var testArray = ['a', 'b', 'c'];
var result = InkArray.map(testArray, function(item, index, arr) {
return item.toUpperCase();
});
Ink.log(result);
// ['A', 'B', 'C']
});
Simulates python's range(start, stop, step) function.
Creates a list with numbers counting from start until stop, using a for loop.
.
The optional step argument defines how to step ahead. You can pass a negative number to count backwards (see the examples below).
start
The array's first element.stop
Stop counting before this number.step
1Interval between numbers. You can use a negative number to count backwards.Code
Ink.requireModules(['Ink.Util.Array_1'], function(InkArray) {
InkArray.range(0, 10); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
// Using the step argument:
InkArray.range(0, 10, 2); // [0, 2, 4, 6, 8]
InkArray.range(0, 10, 3); // [0, 3, 6, 9]
// Using a negative step to count backwards:
InkArray.range(10, 0, -1); // [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
});
Replacement for Array.prototype.reduce.
Uses Array.prototype.reduce if available.
Produces a single result from a list of values by calling an "aggregator" function.
Falls back to Array.prototype.reduce if available.
array
Input array to be reduced.callback
`function (previousValue, currentValue, index, all) { return {Mixed} }` to execute for each value.initial
Object used as the first argument to the first call of `callback`Example
var sum = InkArray.reduce([1, 2, 3], function (a, b) { return a + b; }); // -> 6
Removes a range of values from the array
arr
Array where the value will be removedfrom
Index of the array where the removal will start removing.rLen
Number of items to be removed from the index onwards.Code
Ink.requireModules(['Ink.Util.Array_1'], function(InkArray) {
var testArray = [ 'value1', 'value2', 'value3', 'value4', 'value5' ];
var newArray = InkArray.remove(testArray, 1, 3);
Ink.log(newArray);
// ['value1', 'value5']
});
Shuffles an array.
arr
Array to shuffleCode
Ink.requireModules(['Ink.Util.Array_1'], function(InkArray) {
var testArray = [ 'value1', 'value2', 'value3', 'value4', 'value5' ];
var shuffleArray = InkArray.shuffle(testArray);
Ink.log(shuffleArray);
// ["value2", "value5", "value1", "value3", "value4"]
});
Checks if some element in the array passes a truth test
arr
The array to iterate throughcb
The callback to be called on the array's elements. It receives the value, the index and the array as arguments.context
Object of the callback functionCode
Ink.requireModules(['Ink.Util.Array_1'], function(InkArray) {
var testArray1 = [1, 2, 3, 5, 7, 11, 13];
var testArray2 = [3, 7, 11, 15];
var myTestFunction = function(item, index, arr) {
if((item % 2) === 0) {
return true;
}
return false;
};
var hasOddNumbers;
hasOddNumbers = InkArray.some(testArray1, myTestFunction);
Ink.log(hasOddNumbers); // true
hasOddNumbers = InkArray.some(testArray2, myTestFunction);
Ink.log(hasOddNumbers); // false
});
Sorts an array of objects by an object property
arr
Array of objects to sortkey
Property to sort byCode
Ink.requireModules(['Ink.Util.Array_1'], function(InkArray) {
var testArray = [
{myKey: "value2"},
{myKey: "value5"},
{myKey: "value1"},
{myKey: "value3"},
{myKey: "value4"}
];
var sorted = InkArray.sortMulti(testArray, 'myKey');
Ink.log(sorted);
// [{myKey: "value1"}, {myKey: "value2"}, {myKey: "value3"}, {myKey: "value4"}, {myKey: "value5"}]
});
Removes duplicated values in an array.
arr
Array to filter