[JavaScript] Useful JavaScript Array Object Methods - Explained with Examples.

Beginner Friendly. Explore array methods,join(), push(), pop(), shift(), unshift(), splice(), concat(), sort(), filter(), map(), reduce(), toString().

·

6 min read

[JavaScript] Useful JavaScript Array Object Methods - Explained with Examples.

Array Object Methods That Will Be Covered:

  1. join().

  2. push().

  3. pop().

  4. shift().

  5. unshift().

  6. splice().

  7. concat().

  8. sort().

  9. filter().

  10. map().

  11. reduce().

  12. toString().


1. join()

Join() method allows you to join the elements of an array together.

It receives zero or one parameter (most time you want to put a value in the parameter).

The parameter is the separator.

let brands = ["Apple", "Google", "Amazon", "Microsoft", "Meta"];
// default
console.log(brands.join()); // Apple,Google,Amazon,Microsoft,Meta
// with a separator
console.log(brands.join(" * ")); 
// Apple * Google * Amazon * Microsoft * Meta

2. push()

Push() is used quite often because it allows you to add a new element at the end of your array.

It receives one parameter which is the element that you want to add to your array.

let brands = ["Apple", "Google", "Amazon"];
console.log(brands.push("Netflix"));
// ["Apple", "Google", "Amazon", "Netflix"]

3. pop()

Pop() removes the last element of your array and returns the removed element.

It does not receive any parameters.

let brands = ["Apple", "Google", "Amazon", "Microsoft", "Meta"];
console.log(brands.pop()); // Meta

// Now your array has 4 elements without Meta.

4. shift()

Shift() is similar to pop() but it does the opposite job. Shift() removes the first element of your array and returns that removed element.

It does not receive any parameters.

let brands = ["Apple", "Google", "Amazon", "Microsoft", "Meta"];
console.log(brands.shift()); // Apple

// Now your array has 4 elements without Apple.

5. unshift()

unshift() adds new element(s) to your array and returns the length of your array. The changes will be made to your original array.

You can add as many parameters as you want if you want to add many elements to your array.

let brands = ["Apple", "Google", "Amazon"];
console.log(brands.unshift("Meta", "Netflix")); // 5
console.log(brands);
// ["Meta", "Netflix", "Apple", "Google", "Amazon"]

6. splice()

splice() allows you to add elements anywhere you want unlike how unshift() or push() added the elements to either the first or last index.

The method returns the removed elements in an array type, but changes are made in your original array.

It receives three(3) or more than three(3) parameters.

  1. The index you want to start on

  2. The number of elements to be deleted before adding the new elements.

  3. The third parameter or beyond this, the parameters are elements you want to add.

let brands = ["Apple", "Google", "Amazon", "Microsoft", "Meta"];
// add an element starting from index 1, I wil delete 2 elements ("Google" and "Amazon"), then I will add "Grab"  
console.log(brands.splice(1, 2, "Grab")); // ["Google", "Amazon"]

// Changes are made.
console.log(brands);
// ["Apple", "Grab", "Microsoft", "Meta"]

7. concat()

concat() concatenates arrays together and returns a concatenated array.

It receives multiple parameters, which means, you can concatenate multiple arrays.

let brands1 = ["Apple", "Microsoft", "Meta"];
let brands2 = ["Google", "Amazon"];
let brands3 = ["Netflix"];
console.log(brands1.concat(brands2, brands3));
// ['Apple', 'Microsoft', 'Meta', 'Google', 'Amazon', 'Netflix']

8. sort()

sort() is a method that sorts your array. However, it works with the array that has a String type.

If you want to sort an array that contains numbers, you need to create a function.


Sorting an Array That Contains Strings:

let brands = ["Apple", "Google", "Amazon", "Microsoft", "Meta"];
console.log(brands.sort());
// ['Amazon', 'Apple', 'Google', 'Meta', 'Microsoft']

Sorting an Array That Contains Numbers By Ascending Orders:

let brands = [40, 100, 1, 5, 25, 10];
const brandsAsc = brands.sort(function (a, b) {
    return a - b;
});

console.log(brands);
// [1, 5, 10, 25, 40, 100]

Let me explain how this works.

The two parameters a and b refer to the elements in the array.

If the function finds that a - b is positive, the positions of the two numbers are switched.

For example, 100 - 1 is positive, then those numbers are switched, which makes an array look like this: [40, 1, 100, 5, 25, 10]

Then, 100 - 5 is also positive, then they are switched, which makes:

[40, 1, 5, 100, 25, 10]

This process will be repeated until the function cannot find any positive results.

Then, the array is sorted in ascending order.


Sorting an Array That Contains Numbers By Descending Orders:

let brands = [40, 100, 1, 5, 25, 10];
const brandsAsc = brands.sort(function (a, b) {
    return b - a;
});

console.log(brands);
// [100, 40, 25, 10, 5, 1]

To sort it in descending order, return b - a.

The idea of how this works is explained above.

When ordering in descending order, if b - a is positive, the positions are switched. If negative, they remain the same.

This process is repeated, and the array will be sorted when JavaScript cannot find any positive results anymore.


9. filter()

filter() will filter out elements that you do not want.

To do that, you need to create a function that receives an element as a parameter, and the function "must" return true or false.

If true, it will not be filtered out, but if false, it will be filtered out.

let money = 3.8;
const beverage = [
    { name: "coffee", price: 3.0 },
    { name: "latte", price: 3.5 },
    { name: "ade", price: 4.5 },
];

const availabeBeverages = beverage.filter(function (hotDrink) {
    return money >= hotDrink.price; // must return true or false
});

console.log(availabeBeverages);
// {name: 'coffee', price: 3}
// {name: 'latte', price: 3.5}

10. map()

map() can be used when your array contains objects as elements.

With map(), you can modify the objects' keys and values.

const beverage = [
    { name: "coffee", type: "hot", price: 3.0 },
    { name: "latte", type: "hot", price: 3.5 },
    { name: "ade", type: "cold", price: 4.5 },
];

const mapBeverage = beverage.map(function (drink) {
    return {
        nameAndType: drink.type + " " + drink.name,
        price: drink.price,
    };
});

console.log(mapBeverage);
// {nameAndType: 'hot coffee', price: 3}
// {nameAndType: 'hot latte', price: 3.5}
// {nameAndType: 'cold ade', price: 4.5}

Notice that there is a new key "nameAndType".


11. reduce()

reduce() accumulates values.

It receives 4 parameters. The first two parameters are necessary, and the rest are optional.

  1. Accumulator.

    • The value of the accumulator can be previously returned value

    • Or it can be initialized at the bottom of the function. In the example, I initialized it to 0.

  2. Current Value.

  3. Index Number.

  4. Array itself.

Simple calculation to sum up the drink price:

const beverage = [
    { name: "coffee", type: "hot", price: 3.0 },
    { name: "latte", type: "hot", price: 3.5 },
    { name: "ade", type: "cold", price: 4.5 },
];

let beverageTotal = beverage.reduce(function (total, drink) {
    return total + drink.price;
}, 0);

console.log(beverageTotal); // 11

Using accumulator as an array:

const beverage = [
    { name: "coffee", type: "hot", price: 3.0 },
    { name: "latte", type: "hot", price: 3.5 },
    { name: "ade", type: "cold", price: 4.5 },
];

let availableBeverage = beverage.reduce(function (beverageName, drink) {
    if (drink.price <= 4.0) {
        beverageName.push(drink.name);
    }
    return beverageName;
}, []);

console.log(availableBeverage);
// ['coffee', 'latte']

12. toString()

toString() method exists in an array object as well.

It separates an array's elements by commas and turns them into a string type.

let brands = ["Apple", "Google", "Amazon";
console.log(brands.toString()); // Apple,Google,Amazon

Did you find this article valuable?

Support Jay's Dev Blog by becoming a sponsor. Any amount is appreciated!