Arrays - SelfishHellfish/JS_Ref GitHub Wiki

Useful Methods

set array = [1,2,3,4,5];. set is a preferred convention to var
forEach; run through an array and manipulate elements; expects anonymous function as argument:
array.forEach(function(element) {console.log(element+3)})
ES6 shorthand array.forEach(el => console.log(el))
push; append element/value to array:
array.push(4)
pop; remove last element in array; last element is returned
shift; remove first element in array; first element is returned
unshift; prepend element to list
indexOf; returns index given an element value
splice; cut out portion of array; arg1 = start index; arg2 = number of elements
slice; copy a portion of an array; arg1 = start index; arg2 = end index (non-inclusive)
filter; extract certain values from an array based on some condition(s); expects anonymous function as argument: array.filter(function(value) {return value > 3;});
map; manipulate values in array e.g. with math; expects anonymous function as argument
map and filter create new arrays
reverse; flips the order of the elements in an array; manipulates current array rather than creating a new one
concat; combine two arrays
join; generate string from array; argument specifies separator/delimiter
reduce; generates a single value, using all of the elements in an array; takes anonymous function as argument:
array.reduce(function(accumulator, currentValue) {return accumulator + currentValue;});
Arrays cheat sheet