JavaScript Array Tricks

Arrays are list-like objects that come with a several built-in methods to perform traversal and mutation operations. To learn more about Array methods, click here. Here I am going to write a few common array tricks/operations one might come across.

How to duplicate an array?

slice() always returns a new array - the array returned by slice(0) is identical to the input, which basically means it's a cheap way to duplicate an array.

var foo = ["bar","baz"];
var qux = foo.slice(0);
console.log(qux); // ["bar","baz"]

How to compare two arrays?

Use the above examples and try this:

foo == qux; // false
foo === qux; // false

That's obviously not we wanted. The following solutions will do the work.

foo.toString() === qux.toString(); // true
foo.sort().join() == qux.sort().join(); // true

But above solutions doesn't work as you are expected if you care about types. So we need a strict comparison solution:

function arraysCompare(a, b) {
    var i = a.length;
    if (i != b.length)
        return false;
    while (i--) {
        if (a[i] !== b[i])
            return false;
    }
    return true;
};
arraysCompare([1, 2], ["1", "2"]); // false

How to convert array-like objects into arrays?

For example, a DOM NodeList (returned by several DOM methods like getElementsByTagName) is not an array, but it is an array-like object with a length field and is indexable in JavaScript. To convert it to an array, one often uses:

var anchorArray = 
[].slice.call(document.getElementsByTagName('a'), 0);

Or

var anchorArray = 
Array.prototype.slice.call(document.getElementsByTagName('a'), 0);

The above tricks only work for array-like objects, aka arguments object, meaning that the object has a length property. If it's a normal object, we need a function like this:

var arr = [];

for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
      arr.push(obj[key]);  
    }
}
console.log(arr);

Yang Zhao

Read more posts by this author.


Comment