CodeinWP CodeinWP

JavaScript Array Methods Reference

JavaScript Array Methods ReferenceBack in July I wrote a post called JavaScript String Methods Reference, outlining many of the ways strings can be manipulated in JavaScript.

Another area where JavaScript has a number of different methods available for use is Array manipulation, which I’ll cover in this JavaScript array methods reference. As usual, I’ll do my best to keep it simple and accurate, but if I’ve erred or if you think I’ve omitted anything important, please comment.

Create an Array

To create an array you can do one of the following:

var myArray = new Array();
var myArray = []; // the recommended way

The first of those is an array constructor. The second (which is the recommended way to do this) is an array literal.

You can also create an array with a set amount of “slots” in the array. The following creates an array with 30 empty slots, each holding a value of undefined:

var myArray = new Array(30);

And you can create an array with items already defined:

var myArray = new Array("apples", "oranges", "pears", "watermelons");

You can also do this with the array literal notation:

var myArray = ["apples", "oranges", "pears", "watermelons"];

Test if Object is an Array

To find out if an object is a valid array, you can use Array.isArray():

var myArray = "Misnomer";
var myArray2 = ["keeping", "things", "real"];
console.log(Array.isArray(myArray)); // false
console.log(Array.isArray(myArray2)); // true

Since myArray is not an array, Array.isArray() returns false. But myArray2 is an array, so it returns true.

Get or Set Array Length

To find out how many items are in an array, or how long an array is, you can use the length property:

var myArray = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
console.log(myArray.length); // 5

Interestingly, you can also redefine the size of the array using length:

var myArray = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
myArray.length = 3;
console.log(myArray); // ["Monday", "Tuesday", "Wednesday"]

As shown above, after defining a 5-item array, we then set the length to “3”, which removes the final two items.

Conversely, you can add items using the length property:

var myArray = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
myArray.length = 7;
console.log(myArray);
// ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", undefined × 2]

Although that is possible, it’s limited in usefulness, because the two new values are “undefined”, even though the length is now 7 instead of 5.

Getting and Setting Array Values

To read the value of an item in an array, you can do this:

var myArray = ["1984", "Jane Eyre", "Moby Dick", "Charlotte's Web"];
console.log(myArray[2]); // Moby Dick

The number in square brackets is the index (or position) of the item you want to read or access.

For beginners: Remember that indexes start at zero.

To change the value of an array item:

var myArray = ["It", "ain't", "over", "until", "it's over"];
console.log(myArray[4]); // it's over

myArray[4] = "the fat lady sings";
console.log(myArray); // ["It", "ain't", "over", "until", "the fat lady sings"]

Here we use the square bracket notation to set a new value for the fifth item in the array, which changed from “it’s over” to “the fat lady sings”.

Convert Array to String

You can convert an array to a string, which preserves commas:

var myArray = ["csv", "files", "ftw"];
myArray = myArray.toString();
console.log(myArray); // csv,files,ftw

You can also do this with toLocaleString():

var myArray = ["who", "needs", "spaces"];
myArray = myArray.toLocaleString();
console.log(myArray); // who,needs,spaces

And you can use the join() method to do this:

var myArray = ["parent", "child", "dog"];
myArray = myArray.join();
console.log(myArray); // parent,child,dog

By default, the array items are joined with join() by commas. But you can join the elements using something other than a comma:

var myArray = ["apples", "oranges", "pears"];
myArray = myArray.join("|");
console.log(myArray); // apples|oranges|pears

Adding Items to an Array

You can use the length property to add a new item to the end of an array:

var myArray = ["Apple", "Microsoft", "Google", "Facebook"];
myArray[myArray.length] = "Yahoo!";
console.log(myArray); // ["Apple", "Microsoft", "Google", "Facebook", "Yahoo!"]

This works because the array is zero-based, whereas the length just counts from 1. So the length will always be equal to the array’s index + 1, thus providing an easy way to throw a new item onto the end of an array.

Oddly, you can add an item to a position much higher than the current length of the array:

var myArray = ["Jimi Hendrix", "Eric Clapton", "Jimmy Page", "Keith Richards"];
myArray[99] = "Lindsey Buckingham";
console.log(myArray);
// ["Jimi Hendrix", "Eric Clapton", "Jimmy Page", "Keith Richards", undefined × 95, "Lindsey Buckingham"]
console.log(myArray.length); // 100

As shown in the trailing comment, this will add 95 blank slots to the end of the array, followed by the value “Lindsey Buckingham”. This makes the length equal to 100.

You also have the option of adding to an array using the push() method:

var myArray = ["Paul McCartney", "John Lennon", "George Harrison"];
myArray.push("Ringo Starr", "George Martin");
console.log(myArray);
// ["Paul McCartney", "John Lennon", "George Harrison", "Ringo Starr", "George Martin"]

The push() method always returns the array’s new length (in this case 5).

You can also add an item to an array using splice():

var myArray = ["acorn", "beech", "mongongo", "macadamia"];
myArray.splice(2, 0, "cashew"); // adds "cashew" into index 2
console.log(myArray); // ["acorn", "beech", "cashew", "mongongo", "macadamia"]

When the second argument is zero, this means no items are removed, and so any subsequent arguments are added to the array in the position indicated in the first argument.

Removing Items from an Array

To delete an item from an array is a little more difficult. In order to remove the last item in an array, you can use pop():

var myArray = ["7-up", "Sprite", "Ginger Ale", "Lemonade"];
myArray.pop();
console.log(myArray); // ["7-up", "Sprite", "Ginger Ale"]

The pop() method always removes the last item and returns that removed item.

You can also use the splice() method:

var myArray = ["cassava", "nutmeg", "lupin", "rhubarb"];
myArray.splice(2, 1); // removes 1 element from index 2
console.log(myArray); // ["cassava", "nutmeg", "rhubarb"]

Unlike using splice() to add an item, this time we’ve provided a second argument of 1, meaning we want one item removed at the specified index (2, or the third item). This results in the “lupin” item being deleted.

You can also remove an array element using the delete operator:

var myArray = ["Byte Bandit", "Eliza", "Jeefo", "Michelangelo"];
console.log(myArray.length); // 4
delete myArray[1]; //
console.log(myArray.length); // 4
console.log(myArray); // ["Byte Bandit", undefined × 1, "Jeefo", "Michelangelo"]

A few important things to note here: First, using delete in this way does not change the length of the array (even if you delete the last item). Second, all this does is change the array item to a value of “undefined”, so this would be the same as doing myArray[1] = undefined.

A powerful way to easily remove items from an array is using John Resig’s Array.remove. Here it is with some examples of use, as taken from his page:

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

// Remove the second item from the array
array.remove(1);
// Remove the second-to-last item from the array
array.remove(-2);
// Remove the second and third items from the array
array.remove(1,2);
// Remove the last and second-to-last items from the array
array.remove(-2,-1);

You might also want to consider a similar solution by Viral Patel, one of the functions in Underscore.js, or jQuery’s grep().

JavaScript additionally has the shift() method, which lets you remove and get the value of the first item in any array. See the following:

var myArray = ["Matt Kramer", "Jason Bieler", "Tom Defile", "Phil Varone"];
console.log(myArray.length); // 4
var firstItem = myArray.shift();
console.log(firstItem); // Matt Kramer
console.log(myArray.length); // 3
console.log(myArray); // ["Jason Bieler", "Tom Defile", "Phil Varone"]

With shift(), we were able to remove the first item, storing it in its own variable outside the array. As a result, the length of the array from four items to three.

This can be useful in conjunction with push(). Using both together lets you effectively queue the items in the array, keeping the array the same length while retrieving the first item and adding another one to the end.

Conversely, you have the option to use unshift() to add one or more items to the front of the array:

var myArray = ["apito", "castanets", "maraca"];
console.log(myArray.length); // 3
myArray.unshift("chime bar", "tan-tan");
console.log(myArray.length); // 5
console.log(myArray); // ["chime bar", "tan-tan", "apito", "castanets", "maraca"]

With unshift() combined with pop(), you can queue the items in the opposite direction, adding items to the front of the array and removing items from the back.

Reverse and Sort Items in an Array

To reverse the order of array items, you can use reverse():

var myArray = ["countdown", "final", "the"];
console.log(myArray); // ["countdown", "final", "the"]
myArray = myArray.reverse();
console.log(myArray); // ["the", "final", "countdown"]

To sort the elements of an array alphabetically, use sort():

var myArray = ["xylophones", "zebras", "juggernauts", "avocados"];
console.log(myArray); // ["xylophones", "zebras", "juggernauts", "avocados"]
myArray = myArray.sort();
console.log(myArray); // ["avocados", "juggernauts", "xylophones", "zebras"]

But this won’t work correctly on numbers, because, as MDN points out, “elements are sorted by converting them to strings and comparing strings in lexicographic … order”:

var myArray = [0, 4, 12, 17, 103];
console.log(myArray); // [0, 4, 12, 17, 103]
myArray = myArray.sort();
console.log(myArray); // [0, 103, 12, 17, 4]

To combat this, you can pass a compare function into sort(). Here’s a simple example that lets numbers be ordered:

function compareNumbers(a, b) {
  return a - b;
}

var myArray = [0, 103, 12, 17, 4];
console.log(myArray); // [0, 103, 12, 17, 4]
myArray = myArray.sort(compareNumbers);
console.log(myArray); // [0, 4, 12, 17, 103]

As shown here, with this simple function passed into sort, if the array contains numbers, it will be sorted numerically.

Combining Arrays

You can combine two or more arrays to get a new array that has all the items from the provided arrays:

var myArray = ["Jay Ferguson", "Andrew Scott"];
var myArray2 = ["Chris Murphy", "Patrick Pentland"];
var myNewArray = myArray.concat(myArray2);
console.log(myNewArray);
// ["Jay Ferguson", "Andrew Scott", "Chris Murphy", "Patrick Pentland"]

And of course, instead of passing in a reference to an array, you can simply supply the actual array values you want to add:

var myArray = ["Jay Ferguson", "Andrew Scott"];
var myNewArray = myArray.concat("Chris Murphy", "Patrick Pentland");
console.log(myNewArray);
// ["Jay Ferguson", "Andrew Scott", "Chris Murphy", "Patrick Pentland"]

Slicing an Array

You can create a new array consisting of one or more items in an existing array using slice():

var myArray = ["Vocals", "Bass", "Guitar", "Drums", "Apples", "Oranges"];
var myNewArray = myArray.slice(4);
console.log(myNewArray); // ["Apples", "Oranges"]

The slice() method takes one or two arguments. If one argument is supplied, a new array is created using all the items in the array starting from that index. When two are provided, a new array is created starting from argument one and ending in the item prior to argument two. Let’s use the previous example to get the first four items:

var myArray = ["Vocals", "Bass", "Guitar", "Drums", "Apples", "Oranges"];
var myNewArray = myArray.slice(0, 4);
console.log(myNewArray); // ["Vocals", "Bass", "Guitar", "Drums"]

So although 4 in this case means “the fifth item in the array” and thus takes everything before that item, you could think of it as “extract four items”, even though technically that’s not what it represents.

Replace an Array Item

We’ve used splice() to delete and add items to an array, but you can also use it to replace an item in an array with one or more new items:

var myArray = ["Rivers Cuomo", "Patrick Wilson", "Brian Bell", "Matt Sharp"];
myArray.splice(3, 1, "Scott Shriner"); // replaces 1 element from index 3
console.log(myArray);
// ["Rivers Cuomo", "Patrick Wilson", "Brian Bell", "Scott Shriner"]

The splice() method always returns an array containing any items that were removed. So in the example just given, the return value would be an array of one item, with the item being “Matt Sharp”.

Conclusion

This should provide you with more or less everything you’ll need to manipulate arrays with vanilla JavaScript. There are some other methods and properties listed on MDN that I didn’t include in this post. Those are only supported in IE9+, so they may not be as useful.

Got anything to add? Or know of any useful libraries that help with these? Comment below.

Photo credit: Gold box array from Bigstock

14 Responses

  1. Sumair says:

    Nice and informative article on JS array.

    I also need to know more about how to manage JS in big applications and what are the common standards when writing extensive JS for a big application.

  2. Miguel says:

    Now, I know everything about arrays and string! :)

    Thank you for this summary!

  3. Doug Spence says:

    Great post and I must say here I have ever seen such article before..

  4. Sethu nachammai says:

    Thank you..Nice article :)

  5. Nat says:

    Great post, Thank you very much ^_^

  6. Definitely a good primer and covers the basics. There are still some really weird array functions out there I have yet to fully wrap my head around:

    reduce
    some
    map

  7. jason says:

    i think underscore is a good library to help when you’re dealing with arrays. If you’re ever really deep into the array stuff and jquery just doesn’t seem to be taking you as far as you need to go then adding underscore on top of that should have something to offer you.

  8. Joan Miquel Torres says:

    ERROR:

    Using “Array.prototype.remove = …” to define new property for arrays is a bad idea because this property will become enumerable.

    Example:

    $ node
    > Array.prototype.remove = function(){}
    [Function]
    > for (i in []) console.log(i);
    remove

    You must (or, at least, this is the only way I know) use Object.defineProperty() to explicitly set enumerable attribute to false.

    Otherwise you will end up with strange behaviours when scanning arrays with for() or similar sentences.

  9. mbasanna says:

    I have 2 Arrays: english[]={“a”, “aa”, “i”, “ii”, . . .}, kannada[]={“\u0043”, “\u0044”, “\u0045”, “\u0046”, . . .} and a Textarea to type.
    Whenever I type “aa” in the Textarea the corresponding “\u0044” must appear in the textarea. Similarly “i” to be replaced by “\u0045”, and so on.
    That is all! This must happen whenever I repeat.
    I need a JAVASCRIPT program to transliterate from English to Kannada.
    Any alternative solution welcome!

  10. khalidj says:

    Thanks Its very good Lesson
    I have som Add
    in splice() finction can be add some values in one time
    var arr=new Array(“A”,”D”,”E”);
    arr.splice(1,0,”B”,”C”);
    arr=A,B,C,D,E
    arr.splice(1,2,”X”,”Y”);//to main array before splice above!!
    arr=A,X,Y

Leave a Reply

Comment Rules: Please use a real name or alias. Keywords are not allowed in the "name" field and deep URLs are not allowed in the "Website" field. If you use keywords or deep URLs, your comment or URL will be removed. No foul language, please. Thank you for cooperating.

Markdown in use! Use `backticks` for inline code snippets and triple backticks at start and end for code blocks. You can also indent a code block four spaces. And no need to escape HTML, just type it correctly but make sure it's inside code delimeters (backticks or triple backticks).