Note: these "extra methods," which are "higher-order" functions, ignore holes in the array (i.e.: [“apples”, , , , “oranges”]). they also have more arguments than shown here -- best to look them up for more info!
Note: array-
like objects, for example
arguments
and
NodeLists
, can also make use of these methods.
arr.some(callback)
arr.every(callback)
• returns a boolean value. returns true if
some or
every element in the array meets the evaluation. example:
var a = [1,2,3];
var b = a.every(function(item){
return item > 1;
}); // false
arr.reduce(function(prev, next){..}, startVal)
arr.reduceRight(function(prev, next){..}, startVal)
• returns a value.
reduce employs a callback to run through the elements of the array, returning "prev" to itself with each iteration and taking the next "next" value in the array. for it's first "prev" value it will take an optional "startVal" if supplied. an interesting example:
var arr = ["apple", "pear", "apple", "lemon"];
var c = arr.reduce(function(prev, next) {
prev[next] = (prev[next] += 1) || 1;
return prev;
}, {});
// objCount = { apple: 2, pear: 1, lemon: 1 }
arr.filter(function(){..})
• returns an array.
filter returns an array of elements that satisfy a given callback. example:
var arr2 = ["jim", "nancy", "ned"];
var letter3 = arr2.filter(function(item) {
return (item.length === 3);
});
console.log(letter3); // ['jim', 'ned']
arr.sort(function(){..})
• returns
the original array, mutated.
sort returns the elements sorted with a given criteria. for example:
var stock = [{key: “r”, num: 12}, {key: “a”, num: 2}, {key: “c”, num: 5}];
var c = stock.sort(function(a,b) {
return a.num - b.num;
} ); // [ { key: ‘a', num: 2 }, { key: ‘c', num: 5 }, { key: ‘r', num: 12 } ]
arr.map()
• returns an array.
map goes over every element in the array, calls a callback on the element, and sets an element in the new array to be equal to the return value the callback. for example:
var stock = [{key: "red", num: 12}, {key: "blue", num: 2}, {key: "black", num: 2}];
var b = stock.map(function (item){
return item.key;
}) // ["red","blue","black"]
arr.forEach()
• no return value.
forEach performs an operation on all elements of the array. for example:
var arr = [“jim”, “mary”];
a.forEach (function (item) {
console.log("I simply love “ +item);
}); // “I simply love jim”, “I simply love mary"
Note: you can combine array methods in a
chain where the result of the leftmost operation is passed to the right as such:
array.sort().reverse()...
Created By
Metadata
Favourited By
and 19 more ...
Comments
pits, 14:33 28 Jan 24
Can you check the line-breaks in some sections?
Add a Comment
Related Cheat Sheets