Quick actions

cmd+k|ctrl+k

Navigation

Languages

Array Object Methods - 1

Snippet info

Language

JavaScript

Visibility

public

Author

apizzimenti

Created

2016-03-19T18:10:52Z

Updated

2016-03-19T18:10:52Z

/*
Arrays are hugely useful in any programming language, and JavaScript is no
exception. JavaScript includes a variety of built-ins to help with arrays.
*/

var array = [1, 2, 3, 4];

// unshift(value) places the argument at the beginning of the array

array.unshift(0);

// push(value) places the argument at the end of the array

array.push(5);

// shift() gets the first value of the array and returns it

array.shift();

// pop() gets the last value of the array and returns it

array.pop();

// find(function(object)) finds the value in the array that matches the test and returns that *value*
// this is an ES6 function, so using it with node or modern browsers requires extensions or transpiling
// findIndex(function(object)) does the same thing as find(), but returns the *index*

/*
function is_three(value) {
    return value === 3;
}

array.find(is_three);
*/

// reduce(function(object)) applies a function to all values in the array to reduce it a single value

function sum(a, b) {
    return a + b;
}

array.reduce(sum);
INFO