Useful Array Tricks

by kirupa   |   19 August 2017

When you scratch beyond the surface of what arrays are capable of, you enter into some unchartered territory - even if what you are doing seems very reasonable. In this short tutorial, let's chart the unknown and look at how you would accomplish some common array-related tasks such as:

If any of these seem particularly interesting, click on the heading to check it our directly. If not, just read on for some totally-not-boring tricks about our friendly, neighborhood array.

Onwards!

Copying/Cloning an Array

If you want to copy or clone an array to a new variable, you will need to use the slice method without specifying any arguments:

var foo = ["fee", "fi", "fo", "fum"];
var fooCopy = foo.slice();

console.log(fooCopy);

In this example, fooCopy contains a full copy of all the items in the foo array.

Checking if an Object Is an Array

For detecting whether an item is an array or not, you can check the constructor property to see if its value is an Array:

var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Array
console.log(numbers.constructor === Array);

var name = "Homer Simpson";

// Not an array
console.log(name.constructor === Array);

Notice that we are checking for the Array type directly as opposed to the string-based name for it.

Deleting an Array Item

While it is easy to add an item to the array, there is no built-in equivalent for removing an item you've added. You'll need to rely on indexOf and splice to create your own remove functionality:

var evenNumbers = [0, 2, 4, 6, 7, 8, 10];
console.log(evenNumbers.length) // 7 items

var removeIndex = evenNumbers.indexOf(7);

if (removeIndex > -1) {
    evenNumbers.splice(removeIndex, 1);
}

console.log(evenNumbers.length) // 6 items
console.log(evenNumbers);

This approach will completely remove any trace of the array item ever having existed.

For a less intrusive approach, you have the delete keyword. If you try to delete an item from an array using it, the behavior is a bit different. Take a look at the following code snippet to see what happens:

var evenNumbers = [0, 2, 4, 6, 7, 8, 10];
console.log(evenNumbers.length) // 7 items

var removeIndex = evenNumbers.indexOf(7);
delete evenNumbers[removeIndex];

console.log(evenNumbers.length) // 7 items
console.log(evenNumbers);

The only thing that happens using the delete keyword is that the removed item is set to an empty value, but an array entry still remains. That entry will now reference an empty item. The length of the items in the array is still the same as well. That may not be what you expect. If we inspect the output of the above code, here is what evenNumbers will print to our console:

[0, 2, 4, 6, empty, 8, 10]

Where our odd 7 number was, you will see empty instead. The takeaway is this. If you want to retain all of your array indexes, use the delete keyword when you want to remove an item. If you want to fully remove an item and any trace of it from your array, use the indexOf and splice approach instead.

Emptying an Array

To empty out and delete all the contents from your array, the simplest (and also the fastest-ish!) way is to use the totally nontinutive approach where you set the length property of your array to 0:

var myItems = ["apples", "oranges", "bananas", "kiwis"];
console.log(myItems.length); // 4

myItems.length = 0;
console.log(myItems.length); // 0

I know this looks absolutely ridiculous, but try it out for yourself. It totally works!

Making Your Array Items Unique

Thanks to ES6 and the Set object, removing duplicate values from your array is pretty straightforward:

var names = ["Peter", "Joe", "Cleveland", "Quagmire", "Joe"];
var uniqueNames = [...new Set(names)];

console.log(uniqueNames);

The trick is to use the spread (...) operator that expands a collection of items into its individual pieces. There is one wrinkle with this approach. In my testing, the performance of this approach is much slower than the more verbose approach described here. You can see for yourself by running the jsperf test.

Sorting Items

Arrays in JavaScript come with a handy built-in sort method that allows you to specify exactly how to sort. Take a look at the following example where we are sorting some numbers as well as text:

var numbers = [3, 10, 2, 14, 7, 2, 9, 5];
var beatles = ["Ringo", "George", "Paul", "John"];

numbers.sort(compareValues);
beatles.sort(compareValues);

function compareValues(a, b) {
    if (a < b) {
        // if a less than b
        return -1;
    } else if (a > b) {
        // if a greater than b
        return 1;
    } else {
        // a and b are equal
        return 0;
    }
}

console.log(numbers);
console.log(beatles);

We are using one comparison function called compareValues. This function (a callback function to be precise) compares two values that are passed in as an argument, and all we have to do is specify which of the two values should appear first. We do that by returning either -1, 1, or 0. Returning -1 means the first value will appear ahead of the second value. Returning 1 means the first value will appear after the second value. Returning 0 means both values are equal.

Our compareValues function is pretty straightforward. For more involved types of data, you'll need to customize your comparison function appropriately, but even that isn't rocket science. Below is an example of sorting an array of Objects:

var shows = [
{
    name: "Frasier",
    seasons: 11
},
{
    name: "Seinfeld",
    seasons: 9
},
{
    name: "Friends",
    seasons: 10
},
{
    name: "Cheers",
    seasons: 11
},
{
    name: "Animaniacs",
    seasons: 5
},
{
    name: "Everybody Loves Raymond",
    seasons: 9
}
];

function showComparison(a, b) {
    if (a.seasons < b.seasons) {
        // if a less than b
        return -1;
    } else if (a.seasons > b.seasons) {
        // if a greater than b
        return 1;
    } else {
        // a and b are equal
        return 0;
    }
}

var sortedShows = shows.sort(showComparison);
console.log(sortedShows);

In this example, we are sorting television shows by the number of seasons. Each television show is represented as an Object in our array. Notice how we have our showComparison function defined. Instead of comparing the two values directly, we are dotting in to the seasons value to help determine which show should appear first.

But wait! There is more!

There are more things you can do with arrays that are a bit more involved than simple tricks. Those I've covered separately in the following articles: Shuffling an Array, Picking a Random Item from an Array, Swapping Items in an Array.

Conclusion

Whew. That's a lot of random array-related stuff to digest, but these tricks will come in handy given how often you will use arrays in your day-to-day coding life. I guarantee it. If there are additional array tricks that you know about that I didn't cover, jump into the comments and post them.

If you have a question about this or any other topic, the easiest thing is to drop by our forums where a bunch of the friendliest people you'll ever run into will be happy to help you out!

THE KIRUPA NEWSLETTER

Get cool tips, tricks, selfies, and more...personally hand-delivered to your inbox!

( View past issues for an idea of what you've been missing out on all this time! )

WHAT DO YOU THINK?

NEWSLETTER

No spam. No fluff. Just awesome content sent straight to your inbox!

Awesome and high-performance web hosting!
BACK TO TOP
new books - yay!!!