JavaScripter

Array methods

In computer programming, an array is a set of data elements stored under the same name. Arrays can be created to hold any type of data, and each element can be individually assigned and read. There can be arrays of numbers, characters, sentences, boolean values, and so on.



Empty an array

var meals = ['breakfast', 'lunch', 'dinner'];

array.splice(0, meals.length);
// OR
array.length = 0

Clone an array

var meals = ['breakfast', 'lunch', 'dinner'];

var copy = meals.slice()
// OR
var copy = [...meals]

Get last item

var meals = ['breakfast', 'lunch', 'dinner'];

meals[meals.length - 1];
// OR
meals.slice(-1)[0];

Get consecutive items

var meals = ['breakfast', 'brunch', 'lunch', 'dinner'];

meals.slice(2,4);

nightTimeMeals =

Remove first item

var meals = ['breakfast', 'lunch', 'dinner'];

meals.shift();

Remove last item

var meals = ['breakfast', 'lunch', 'dinner'];

meals.pop();

Remove single item at a specific index

var meals = ['breakfast', 'lunch', 'dinner'];

meals.splice(1, 1);

Remove several items

var meals = ['breakfast', 'lunch', 'dinner'];

meals.splice(1, 2);

Add new item(s) to beginning

var meals = ['lunch', 'dinner'];

meals.unshift('breakfast');

Add new item(s) to end

var meals = ['breakfast', 'lunch', 'dinner'];

meals.push('supper');

Add new item(s) at a specific index

var meals = ['breakfast', 'lunch', 'dinner'];

meals.splice(1, 0, 'brunch', 'more brunch');

Overwrite item at a specific index

var meals = ['breakfast', 'lunch', 'dinner'];

meals[1] = 'brunch';
// OR
meals.splice(1, 1, 'brunch');

Reverse an array

var meals = ['breakfast', 'lunch', 'dinner'];

meals.reverse();

Sort in numerical order

var numbers = [1438,2605,794,3947,6241,11745,2585];

numbers.sort(function(a, b) {
    return a - b;
});

Sort in alphabetical order

var meals = ['dinner', 'supper', 'breakfast', 'lunch'];

meals.sort();

Shuffle array

function randomiseArray(arr) {
    var buffer = [], start;

    for(var i = arr.length; i >= arr.length && i > 0;i--) {
        start = Math.floor(Math.random() * arr.length);
        buffer.push(arr.splice(start, 1)[0])
    };

    return buffer;
}

Join array items into a string

var meals = ['breakfast', 'lunch', 'dinner'];

meals.join(' AND ');

Split string into an array

var string = "breakfast AND lunch AND dinner"

var meals = string.split(' AND ');

Join two arrays together

var dayTimeMeals = ['breakfast', 'lunch'];
var nightTimeMeals = ['merienda', 'dinner'];

var allTheMeals = dayTimeMeals.concat(nightTimeMeals);
// OR
var allTheMeals = [...dayTimeMeals, ...nightTimeMeals]

Find array intersection

var animals = ['fish', 'bird', 'gorilla', 'dog']
var mammals = ['horse','gorilla','human','dog']

animals.filter((animal) => mammals.indexOf(animal) !== -1)

Remove duplicates from array

var numbers = [1, 1, 1, 5, 6, 4]

numbers = [...new Set(numbers)]

Map items to a new array

var meals = ['breakfast', 'lunch', 'dinner'];

meals.map((meal, index) => console.log(`I like ${meal} - ${index}`))

Filter an array

var meals = ['breakfast', 'lunch', 'dinner', 'supper']

meals.filter((meal) => meal !== 'breakfast')

Reduce an array

var numbers = [30, 41, 466, 44];

var sum = numbers.reduce((total, amount) => total + amount);

Execute a function once per array item

var meals = ['breakfast', 'lunch', 'dinner', 'supper']

meals.forEach((currentValue, index, arr) => console.log(`${currentValue} = ${arr[index]}`))
// OR
for (item in meals) { console.log(meals[item])}

Every item meets a condition

var meals = ['breakfast', 'lunch', 'dinner', 'supper'];

meals.every((meal) => meal.length > 2 )

One item meets a condition

var meals = ['breakfast', 'lunch', 'dinner', 'supper'];

meals.some((meal) => meal === 'lunch')
// OR
meals.includes('lunch')

Find index of an item

var meals = ['breakfast', 'elevenses', 'brunch'];
meals.indexOf('brunch');

Detect an array

var meals = ['breakfast', 'lunch', 'dinner'];

Array.isArray(meals)

Spread array into function parameters

let numbers = [9, 4, 7, 1];

Math.min(...numbers); // 1

Clone an object

var myObj = {a: 1, b: {c: 2, d: 3}}

var myObj2 = JSON.parse(JSON.stringify(myObj))

Loop over object’s key value pairs

var myObj = {a: 1, b: 2, c: 3}
for (var prop in myObj) {
  console.log(prop + myObj[prop])
}

Modify object states

Object.freeze(obj) // prevent mutation and deletion
Object.seal(obj) // allow mutation, but no additions or deletions to state
Object.isFrozen(obj)                                 // Determines if an object was frozen.
Object.isSealed(obj)
Object.keys(obj)
obj.hasOwnProperty(prop)