Available in Chrome 45+ | View on GitHub | Browse Samples
ECMAScript 2015 specification adds additional static methods on Array and instance
methods on Array.prototype.
The Array.from() method converts an array-like object to a true
array. It takes an optional second parameter, which can be used to execute a map
function on each element of the array that is being created.
Array.from(new Set([1, 1, 2, 3])); // [1, 2, 3]
Array.from('hello'); // ["h", "e", "l", "l", "o"]
Array.from('hello', x => x.charCodeAt(0)); // [104, 101, 108, 108, 111]
It comes in handy when dealing with the infamous NodeList
returned by document.querySelectorAll.
var divs = document.querySelectorAll('div');
Array.from(divs).forEach(function(node) {
console.log(node);
});
The Array.of() method creates a new Array instance
with any number of arguments, regardless of their type.
Array.of('hello'); // ["hello"]
Array.of(1, 2, 3); // [1, 2, 3]
Array.of('blink', 182); // ["blink", 182]
The copyWithin() method copies the sequence of array elements
within the array to the position starting at target. The copy is
taken from the index positions of the second and third arguments
start and end. The end argument is
optional and defaults to the length of the array.
[0, 1, 2, 3, 4].copyWithin(target=4, start=0); // [0, 1, 2, 3, 0]
[0, 1, 2, 3, 4].copyWithin(target=0, start=2); // [2, 3, 4, 3, 4]If start is negative, it will be treated as length+start where length is the length of the array. If end is negative, it will be treated as length+end.
[0, 1, 2, 3, 4].copyWithin(target=0, start=3, end=4); // [3, 1, 2, 3, 4]
[0, 1, 2, 3, 4].copyWithin(target=0, start=-2, end=-1); // [3, 1, 2, 3, 4]
The fill() method fills all the elements of an array between an
optional start index and an optional end index with a
static value.
The start argument defaults to 0. The end
argument defaults to the length of the array.
[0, 1, 2, 3, 4].fill(5); // [5, 5, 5, 5, 5]
[0, 1, 2, 3, 4].fill(5, start=2); // [0, 1, 5, 5, 5]
[0, 1, 2, 3, 4].fill(5, start=2, end=4); // [0, 1, 5, 5, 4]
The find() method returns a value in the array, if at least one
element in the array satisfies the provided predicate function. If
not, undefined is returned. find() does not mutate
the array on which it is called.
function startsWithLetterA(element, index, array) {
if (element.startsWith('a')) {
return element;
}
}
var cuteNames = ['jeff', 'marc', 'addy', 'francois'];
cuteNames.find(startsWithLetterA); // "addy"
The findIndex() method returns an index in the array, if at least
one element in the array satisfies the provided predicate
function. If not, -1 is returned. findIndex() does not mutate the
array on which it is called.
function startsWithLetterA(element, index, array) {
if (element.startsWith('a')) {
return element;
}
}
var cuteNames = ['jeff', 'marc', 'addy', 'francois'];
cuteNames.findIndex(startsWithLetterA); // 2