Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Arrayzing - The JavaScript array cheatsheet

Arrayzing - The JavaScript array cheatsheet

This is a work-in-progress cheatsheet for JS arrays. Please feel free to leave a comment if this has helped you or you would like to suggest anything.

Create an array

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

Empty an array

Keeping references intact.

var meals = ['breakfast', 'lunch', 'dinner'];
meals.splice(0, meals.length);

or

var meals = ['breakfast', 'lunch', 'dinner'];
meals.length = 0

Clone an array

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

var copy = meals.slice();
// ['breakfast', 'lunch', 'dinner']

Get last item

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

meals[meals.length - 1];
// 'dinner'

Or

var meals = ['breakfast', 'lunch', 'dinner'];
meals.slice(-1)[0];
// 'dinner'

Remove first item

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

meals.shift();
// 'breakfast'

meals;
// ['lunch', 'dinner']

Remove last item

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

meals.pop();
// 'dinner'

meals;
// ['breakfast', 'lunch'];

Add new item(s) to beginning

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

meals.unshift('breakfast');
// 3 - the array length

meals;
// ['breakfast', 'lunch', 'dinner']

Add new item(s) to end

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

meals.push('supper');
// 2

meals;
// ['breakfast', 'lunch', 'dinner', 'supper'];

Overwrite item at a specific index

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

meals[1] = 'brunch';
// ['breakfast', 'brunch', 'dinner'];

Or

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

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

Add new item(s) at a specific index

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

meals.splice(1, 0, 'brunch', 'more brunch');
// ['breakfast', 'brunch', 'more brunch', 'lunch', 'dinner']

Remove single item at a specific index

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

meals.splice(1, 1);
// ['lunch']

meals;
// ['breakfast', 'dinner']

Remove several items

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

meals.splice(1, 2);
// ['lunch', 'dinner']

meals;
// ['breakfast']

Reverse an array

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

meals.reverse();
// ['dinner', 'lunch', 'breakfast'];

Delimit an array

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

meals.join(' AND ');
// 'breakfast AND lunch AND dinner'

Sort in alphabetical order

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

meals.sort();
// ['breakfast', 'dinner', 'lunch', 'supper']

Sort in numerical order

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

numbers.sort(function(a, b) {
    return a - b;
});
// [794,1438,2585,2605,3947,6241,11745]

Join two arrays together

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

var allTheMeals = dayTimeMeals.concat(nightTimeMeals);
// ['breakfast', 'lunch', 'merienda', 'dinner']

Copy specific item(s)

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

nightTimeMeals = meals.slice(2,4);
// ['dinner', 'supper']

Augment items within an array

var meals = ['breakfast', 'lunch', 'dinner'];
var type = ['king', 'prince', 'pauper'];

meals.map(function(item, i) {
  return item + ' like a ' + type[i];
});
// ["breakfast like a king", "lunch like a prince", "dinner like a pauper"]

Return true if every item meets a condition

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

meals.every(function(item){ return item.length > 0 });
// true

meals.every(function(item){ return item.length > 6 });
// false

Return true if at least one item matches a condition

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

meals.some(function(item){ return item === 'lunch';});
// true

meals.some(function(item){ return item === 'burgers!!';});
//false

Execute a function once per array item

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

meals.forEach(function(currentValue, index, arr){
  console.log(index, currentValue, arr);
});

Filter an array

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

meals.filter(function(item) {
  return item !== 'breakfast';
});
// ['lunch', 'dinner', 'supper'];

Detect an array

ES5 and above

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

Array.isArray(meals)
// true

ES4 and below

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

function isArray(arr) {
  return !!(Object.prototype.toString.call(arr) === '[object Array]');
}

isArray(meals);
// true

Simple FIFO queue

var meals = ['breakfast', 'elevenses', 'brunch'];

meals.shift(); 
meals.push('lunch');

// ['elevenses', 'brunch', 'lunch']

meals.shift()
meals.push('afternoon tea');

// ['brunch', 'lunch', 'afternoon tea']
// ... and so on ...

Find index of an item

ES5 and above

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

ES4 and below

var meals = ['breakfast', 'elevenses', 'brunch'];

function inArray(arr, item){
  var found = -1, 
      i = arr.length; 

  while(--i >= 0) {
    if(arr[i] === item){
      found = i;
      break;
    }
  }
  return found;
}

inArray(meals, 'brunch');
// 2 - the index of the item in the array

inArray(meals, 'dinner');
// -1

Randomise an 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;
}

randomiseArray([0,1,2,3,4]);
// [2,1,0,3,4]

randomiseArray([0,1,2,3,4]);
// [3,2,1,4,0]

randomiseArray([0,1,2,3,4]);
// [1,2,4,0,3]

Chaining methods

var meals = [
  {type: 'breakfast', name: 'Full English', calories: 1500},
  {type: 'breakfast', name: 'Colacao', calories: 260},
  {type: 'breakfast', name: 'Croissant and jam', calories: 520},
  {type: 'breakfast', name: 'Granola with Greek yoghurt and blueberries', calories: 680},
  {type: 'brinner', name: 'Shepherds Pie with strawberry yoghurt', calories: 915},
  {type: 'brinner', name: 'Milky Porridge with beef and green beans', calories: 875},
  {type: 'dinner', name: 'Phad Thai', calories: 750},
  {type: 'dinner', name: 'Chicken Katsu curry and rice', calories: 830},
];

function getMealsByMaxCalories(meals, maxCalories, dailyAllowance) {
  return meals
    .filter(function(meal) {
        return meal.calories <= maxCalories;
    })
    .map(function(meal) {
        return {
            name: meal.name,
            calories: meal.calories,
            percentageOfDailyAllowance: meal.calories / dailyAllowance * 100
        }
    });
}
    
getMealsByMaxCalories(meals, 850, 2000);

/*
[
  {
    "name": "Colacao",
    "calories": 260,
    "percentageOfDailyAllowance": 13
  },
  {
    "name": "Croissant and jam",
    "calories": 520,
    "percentageOfDailyAllowance": 26
  },
  {
    "name": "Granola with Greek yoghurt and blueberries",
    "calories": 680,
    "percentageOfDailyAllowance": 34
  },
  {
    "name": "Phad Thai",
    "calories": 750,
    "percentageOfDailyAllowance": 37.5
  }
]
*/
The MIT License (MIT)
Copyright (c) 2015 Justin Perry
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@Pointy

This comment has been minimized.

Copy link

Pointy commented Aug 7, 2015

Your "reverse sort" comparator function is incorrect. The comparator has to return a negative number, zero, or a positive number, to indicate whether the first argument should be sorted before, the same as, or after the second. Your code returns a boolean, which when interpreted as a number will be either 0 or 1. You cannot, therefore, use the same comparator for sorting arrays of strings in reverse as you would arrays of numbers; numeric sorts can take advantage of the subtraction operator, while string sorts must make comparisons and explicitly return appropriately signed numeric values.

@solderjs

This comment has been minimized.

Copy link

solderjs commented Aug 7, 2015

I'd suggest nixing new Array() as it's generally considered bad form and can have unexpected results - i.e. new Array(27) vs new Array(27, 28) - a leftover from the days when they were trying to emphasize the Java part of JavaScript.

@ourmaninamsterdam

This comment has been minimized.

Copy link
Owner Author

ourmaninamsterdam commented Aug 8, 2015

@Pointy - Good spot and have updated it. Thanks.

@coolaj86 - nixed.

@srujankk

This comment has been minimized.

Copy link

srujankk commented Aug 12, 2015

Get Last item:
meals.slice(-1);
This returns an array with one element not just the last element.

@AngosStudio

This comment has been minimized.

Copy link

AngosStudio commented Aug 13, 2015

First of all great job!! On the Filter an array,

meals.filter(function() (item) { 
    return item !== 'breakfast'; 
});

the correct isn't:

meals.filter(function(item) { 
    return item !== 'breakfast'; 
});
@samirbr

This comment has been minimized.

Copy link

samirbr commented Aug 14, 2015

Another way to randomize array (shuffle):

arr.sort(function () {
    return Math.random() - 0.5;
});

@bluewitch

This comment has been minimized.

Copy link

bluewitch commented Aug 14, 2015

Great resource for my chaotic JavaScript mind. Thanks a bunch!

@microgold

This comment has been minimized.

Copy link

microgold commented Aug 14, 2015

Very nice.

@DrDyne

This comment has been minimized.

Copy link

DrDyne commented Aug 14, 2015

find index of arbitrary attribute :

var myAttr = 'bob';
return array.reduce(function (memo, item, index) {  return item.id === myAttr ? index : memo }, -1);
@UnbrandedTech

This comment has been minimized.

Copy link

UnbrandedTech commented Aug 16, 2015

Awesome! Thank you for putting this together

@mmikowski

This comment has been minimized.

Copy link

mmikowski commented Aug 16, 2015

Very nice indeed! Thank you!

@mr21

This comment has been minimized.

Copy link

mr21 commented Aug 16, 2015

Nice :)

But there is a little mistake here:

Remove several items

var meals = ['breakfast', 'lunch', 'dinner'];
meals.splice(1, 2); // ['breakfast'] <== ['lunch', 'dinner']
meals; // ['breakfast']
@jjlorenzo

This comment has been minimized.

Copy link

jjlorenzo commented Aug 16, 2015

@samirbr your proposed implementation it is not correct.
In general, the modern version of the Fisher-Yates shuffle, designed for computer use, was introduced by Richard Durstenfeld in 1964 and you can see live here. Fisher–Yates Shuffle has O(n) complexity and it is in-place shuffle.

@igoryen

This comment has been minimized.

Copy link

igoryen commented Aug 16, 2015

Awesome! I love resources like that!

@YanlongLai

This comment has been minimized.

Copy link

YanlongLai commented Aug 17, 2015

Nice cheat sheet!

@sprakashg

This comment has been minimized.

Copy link

sprakashg commented Aug 17, 2015

Great Help

@AmolPWaghmare

This comment has been minimized.

Copy link

AmolPWaghmare commented Aug 17, 2015

Thanks for putting it together..

@camposer

This comment has been minimized.

Copy link

camposer commented Aug 17, 2015

Great! Congrats

@funkytaco

This comment has been minimized.

Copy link

funkytaco commented Aug 17, 2015

So should I assume all of these work in ES5, unless otherwise specified?

@hueitan

This comment has been minimized.

Copy link

hueitan commented Aug 18, 2015

Awesome 👍

@Alex-Walgreen

This comment has been minimized.

Copy link

Alex-Walgreen commented Aug 18, 2015

There are multiple errors in your inArray function!

Here's how it should be:

function inArray(arr, item){
  var found = -1,      
      i = arr.length; 

  while(--i >= 0) {      
    if(arr[i] === item){
        found = i;
        break;
    }
  }

  return found;
}

First, --i will NOT find the index if the item is the first in the array when --i yields 0 it evaluates to false and thus the first item in the array is not found. Second, you declare i AND len, no need to declare len as well. Third: you do not break after the item has been found which is very inefficient in large arrays as it will continue to loop through the entire array though the item has already been found. Fourth: you used query to compare to, but it should be item.

@alexbudin

This comment has been minimized.

Copy link

alexbudin commented Aug 18, 2015

When emptying and array doing

meals.length = 0;

is not highly efficient

See some tests done here:
http://jsperf.com/length-equal-0-or-new-array

You can also empty the array by doing:

meals.splice(0,meals.length);

You can also do:

meals = []; 

this is the fastest method (This will set the variable "meals" to a new empty array. This is perfect if you don't have references to the original array "meals" anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original variable "meals")

@tokiio

This comment has been minimized.

Copy link

tokiio commented Aug 18, 2015

nice one, thanks for sharing

@oknoorap

This comment has been minimized.

Copy link

oknoorap commented Aug 18, 2015

good job..

@Harshitsolanki

This comment has been minimized.

Copy link

Harshitsolanki commented Aug 19, 2015

Great job guys..

@patriziosotgiu

This comment has been minimized.

Copy link

patriziosotgiu commented Aug 19, 2015

Nice! Thanks for sharing.

@yodiyo

This comment has been minimized.

Copy link

yodiyo commented Aug 19, 2015

Good stuff. Thanks!

@HeberPcL

This comment has been minimized.

Copy link

HeberPcL commented Aug 20, 2015

Great job! Thx

@ourmaninamsterdam

This comment has been minimized.

Copy link
Owner Author

ourmaninamsterdam commented Aug 20, 2015

@AngosStudio, @mr21, @Alex-Walgreen - well spotted and fixed. thanks.

@alexbudin - My intention for this example one was to keep any references intact rather than assigning a new array. I've updated it to state this. Jim H also mentioned the arr.splice(0, arr.length); method so I'm going to add that too.

@ourmaninamsterdam

This comment has been minimized.

Copy link
Owner Author

ourmaninamsterdam commented Aug 20, 2015

@funkytaco - yep. I'll add some notes to this fact when I get a moment.

@damdeez

This comment has been minimized.

Copy link

damdeez commented Aug 26, 2015

Great stuff, thanks!

@Mkensey

This comment has been minimized.

Copy link

Mkensey commented Sep 9, 2015

Awesome!! Thanks for sharing, this is going to be very helpful.

@danielsdesk

This comment has been minimized.

Copy link

danielsdesk commented Sep 16, 2015

Not sure if this is too "duh" for this awesome list of Array tips, but since you had some slice and splice tips, maybe you'd want to include a tip for replacing an item (or items) in an array, since splice can take additional params to use as replacement?

var meals = ['breakfast', 'lunch', 'dinner'];
meals.splice(1,1,'brunch');  // go to index 1, delete 1 item, put 'brunch' in place of index
// ['breakfast', 'brunch', 'dinner']

// the extra params are all inserted, so you could replace and insert at the same time
var meals = ['breakfast', 'lunch', 'dinner'];
meals.splice(1,1,'brunch','linner'); 
// ['breakfast', 'brunch', 'linner', 'dinner']

EDIT: Maybe I had scrolled through too fast; I see these tips in there now already... Apologies

@mmikowski

This comment has been minimized.

Copy link

mmikowski commented Oct 1, 2015

Please consider merging git@gist.github.com:9669b87fa13c447e5d7e.git. This adds an example to change an array in-place. The easiest way to merge would probably be to simply clone the above repo, and then use a visual diff (kdiff3, meld, etc) to compare the differences. There are proposed changes in only two sections.

@spiritobsessioon

This comment has been minimized.

Copy link

spiritobsessioon commented Jun 29, 2016

Great job!

@sany2k8

This comment has been minimized.

Copy link

sany2k8 commented Aug 14, 2017

Awesome Job. Can you please create another cheat sheet for Javascript Object

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.