5 Useful JavaScript Array Methods

JavaScript’s in-built Array type is as useful as it is powerful. However, there’s always some particular thing you need to do with an array and the language can’t do it with a built-in method.

In the spirit of sharing, here’s 5 that I use in my projects to speed up development and make my code more self explanatory:

Get The Last Item

Returns the last item in the array.

Definition

function getLastItem(theArray) {
    return theArray[theArray.length - 1];
}

Usage

let stereotypes = [
    'Groundskeeper Willie',
    'Fat Tony',
    'Cletus',
    'Comic Book Guy'
];

console.log(
    getLastItem(stereotypes)
);
// 'Comic Book Guy'

Remove Any Element

If you have ever had to remove a specific item from an array, the the programming can be unusually low-level and your intentions non-obvious to the next programmer who reads your code. This function will remove the first occurrence of a specified item or value.

This method returns the remaining items in the array. Note that this doesn’t immutably return a new array, it modifies the array itself.

Definition

function removeElement(theArray, whichElement) {
    var elementIndex = theArray.indexOf(whichElement);
    if (theArray.indexOf(whichElement) !== -1) {
        theArray.splice(elementIndex, 1);
    }
    return theArray;
}

Usage

let stereotypes = [
    'Groundskeeper Willie', 
    'Fat Tony', 
    'Cletus',
    'Comic Book Guy'
];

let mostHilariousStereotype = stereotypes[2];
console.log(
    mostHilariousStereotype
);
// 'Cletus'

removeElement(stereotypes, mostHilariousStereotype);
console.log(
    stereotypes
);
// ['Groundskeeper Willie', 'Fat Tony', 'Comic Book Guy'];

Push If Not Present

This method will push the provided argument value to the array if it’s not currently present in the array itself. If the provided argument value is already present in the array, the call does nothing.

This method returns the new values in the array. Note that this can modify the original array, so it’s not immutable.

Definition

function pushIfNotPresent(theArray, element) {
        if (theArray.indexOf(element) === -1) {
            theArray.push(element);
        }
        return theArray;
    };

Usage

let stereotypes = [
    'Groundskeeper Willie', 
    'Fat Tony', 
    'Cletus',
    'Comic Book Guy'
];

pushIfNotPresent(stereotypes, 'The Rich Texan');
console.log(
    stereotypes
);
// -&gt ['Groundskeeper Willie', 'Fat Tony', 'Cletus', 'Comic Book Guy', 'The Rich Texan'];
// ('The Rich Texan' was not already in the array, so it was successfully added.)

pushIfNotPresent(stereotypes, 'Fat Tony');
console.log(
    stereotypes
);
// ['Groundskeeper Willie', 'Fat Tony', 'Cletus', 'Comic Book Guy', 'The Rich Texan'];
// ('Fat Tony' was already in the array, so this method call had no effect.)

Retrieve Unique Values

This one comes from Pedro L on StackOverflow.

This method immutably returns an array of values from the called array, but without any of the duplicated values. Each value will only appear once.

Definition

function getUniques(theArray) {
    return theArray.reduce(function(p, c) {
        if (p.indexOf(c) < 0) p.push(c);
        return p;
    }, []);
}

Usage

let thingsToRemember = [
    'Dental Plan',
    'Lisa Needs Braces',
    'Dental Plan',
    'Lisa Needs Braces'
    'Dental Plan',
    'Lisa Needs Braces'
];

console.log(
    getUniques(thingsToRemember)
);
// ['Dental Plan', 'Lisa Needs Braces']

Replace Contents

Sometimes you need to completely change what’s in an array without losing its reference. This will remove all the items out of an array and re-fills it with new values.

This method returns the new values in the array. It modifies the original array and is not immutable.

Definition

/**
 * Mutably replaces all the items in the array with `newValues`.
 *
 * @param {Array} theArray - the original array we're working with
 * @param {*|Array} newValues - can be a single item (so the array will now be [thing] or list of new items to become the array's new contents.
 * @returns {Array} - Returns `theArray` (the array modified in-place)
 */
function replaceValues(theArray, newValues) {
    if ((newValues instanceof Array) === false) {
        newValues = [newValues];
    }

    /**
     * Remove all the current items
     */
    theArray.splice(0, theArray.length);

    /**
     * call `splice` again, but this time it inserts each value of `newValues`
     */
    theArray.splice.apply(
        theArray,
        /**
         * [0,0] is the first two arguments of `Array.splice`, and each newValues item is passed as an argument
         * afterwards.
         */
        [0,0].concat(newValues)
    );

    return theArray;
}

Usage

let menuItems = [
    'Krusty Burger with cheese',
    'Krusty partially gelatinated nondairy gum-based beverages'
];

replaceItems(menuItems, [
    'Quarter Pounder with cheese',
    'Shakes'
]);

console.log(menuItems);
// [ 'Quarter Pounder with cheese', 'Shakes']

Feel free to use these methods for your own project, or even make some sort of SuperArray class. Also, if you’ve written any other Array functions that get common use, be sure to let me know!


Note: an earlier version of this article presented these methods as extensions to the Array.prototype object. Even though I warned that I did this for display purposes only, I saw instances of verbatim copying.

Please remember, augmenting a built-in data type should be reserved for advanced use only!