adekunle@adeyemi.tech

JavaScript Arrays and Objects: Exploring Their Methods and Usage

Two fundamental data structures in JavaScript are arrays and objects

09/09/2023

Introduction

JavaScript is a versatile and widely used programming language that allows developers to create dynamic and interactive web applications. Two fundamental data structures in JavaScript are arrays and objects. Understanding how to work with arrays and objects, along with their methods, is crucial for building efficient and organized code. In this article, we’ll explore JavaScript arrays and objects, along with some of their most commonly used methods, accompanied by examples.

JavaScript Arrays

Introduction to Arrays

An array is a collection of values, each identified by an index or a key. In JavaScript, arrays are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on. Arrays can store various data types, including numbers, strings, objects, and even other arrays.

Here’s how you can declare an array:

const fruits = ["apple", "banana", "cherry"];

Common Array Methods

  1. push() and pop()

    • push(): Adds one or more elements to the end of an array.
    fruits.push("date");
    // Result: ["apple", "banana", "cherry", "date"]
    • pop(): Removes the last element from an array.
    const removedFruit = fruits.pop();
    // Result: removedFruit = "date", fruits = ["apple", "banana", "cherry"]
  2. unshift() and shift()

    • unshift(): Adds one or more elements to the beginning of an array.
    fruits.unshift("grape");
    // Result: ["grape", "apple", "banana", "cherry"]
    • shift(): Removes the first element from an array.
    const removedFruit = fruits.shift();
    // Result: removedFruit = "grape", fruits = ["apple", "banana", "cherry"]
  3. indexOf() and lastIndexOf()

    • indexOf(): Returns the first index at which a specified element is found in an array.
    const index = fruits.indexOf("banana");
    // Result: index = 1
    • lastIndexOf(): Returns the last index at which a specified element is found in an array.
    const lastIndex = fruits.lastIndexOf("cherry");
    // Result: lastIndex = 2
  4. splice()

    • splice(): Changes the contents of an array by removing, replacing, or adding elements at a specified index.
    fruits.splice(1, 2, "orange", "pear");
    // Result: ["apple", "orange", "pear"]
  5. concat()

    • concat(): Combines two or more arrays and returns a new array.
    const moreFruits = ["strawberry", "blueberry"];
    const combinedFruits = fruits.concat(moreFruits);
    // Result: ["apple", "orange", "pear", "strawberry", "blueberry"]
  6. forEach()

    • forEach(): Executes a provided function once for each array element.
    fruits.forEach((fruit) => {
        console.log(fruit);
    });
    // Output: "apple", "orange", "pear"

JavaScript Objects

Introduction to Objects

An object is a collection of key-value pairs, where each key is a string (or symbol), and each value can be of any data type. Objects are used to represent structured data and are fundamental to JavaScript.

Here’s how you can declare an object:

const person = {
    firstName: "John",
    lastName: "Doe",
    age: 30,
};

Common Object Methods

  1. Object.keys() and Object.values()

    • Object.keys(): Returns an array of an object’s keys.
    const keys = Object.keys(person);
    // Result: ["firstName", "lastName", "age"]
    • Object.values(): Returns an array of an object’s values.
    const values = Object.values(person);
    // Result: ["John", "Doe", 30]
  2. Object.entries()

    • Object.entries(): Returns an array of an object’s key-value pairs as arrays.
    const entries = Object.entries(person);
    /* Result:
    [
        ["firstName", "John"],
        ["lastName", "Doe"],
        ["age", 30]
    ]
    */
  3. hasOwnProperty()

    • hasOwnProperty(): Checks if an object has a specific property and returns a boolean.
    const hasAge = person.hasOwnProperty("age");
    // Result: true
  4. delete

    • delete: Removes a property from an object.
    delete person.age;
    // The "age" property is removed from the "person" object
  5. Object.assign()

    • Object.assign(): Copies the values of all enumerable properties from one or more source objects to a target object.
    const newPerson = Object.assign({}, person, { age: 35 });
    // Result: newPerson = { firstName: "John", lastName: "Doe", age: 35 }

JavaScript also provides a rich set of methods for arrays and arrays of objects. Let’s explore some additional array methods and how they can be used, especially when dealing with arrays of objects.

Additional Array Methods

  1. map()

    • map(): Creates a new array by applying a function to each element of the original array.
    const numbers = [1, 2, 3, 4];
    const doubled = numbers.map((num) => num * 2);
    // Result: doubled = [2, 4, 6, 8]
  2. filter()

    • filter(): Creates a new array with all elements that pass a specified test.
    const scores = [75, 80, 92, 60, 88];
    const passingScores = scores.filter((score) => score >= 70);
    // Result: passingScores = [75, 80, 92, 88]
  3. reduce()

    • reduce(): Applies a function to an accumulator and each element of the array, reducing it to a single value.
    const numbers = [1, 2, 3, 4];
    const sum = numbers.reduce((acc, num) => acc + num, 0);
    // Result: sum = 10
  4. sort()

    • sort(): Sorts the elements of an array in place and returns the sorted array.
    const fruits = ["banana", "apple", "cherry"];
    fruits.sort();
    // Result: fruits = ["apple", "banana", "cherry"]
  5. reverse()

    • reverse(): Reverses the order of elements in an array.
    const numbers = [1, 2, 3, 4];
    numbers.reverse();
    // Result: numbers = [4, 3, 2, 1]

Arrays of Objects

When working with arrays of objects, you can combine array methods with object property access to perform various operations.

Let’s assume we have an array of objects representing people:

const people = [
    { name: "Alice", age: 30 },
    { name: "Bob", age: 25 },
    { name: "Charlie", age: 35 },
];
  1. find() and findIndex()

    • find(): Returns the first element in an array that satisfies a provided testing function.
    const person = people.find((p) => p.age === 25);
    // Result: person = { name: "Bob", age: 25 }
    • findIndex(): Returns the index of the first element in an array that satisfies a provided testing function.
    const index = people.findIndex((p) => p.name === "Charlie");
    // Result: index = 2
  2. some() and every()

    • some(): Checks if at least one element in an array satisfies a provided condition.
    const hasYoungPerson = people.some((p) => p.age < 30);
    // Result: hasYoungPerson = true
    • every(): Checks if all elements in an array satisfy a provided condition.
    const allAdults = people.every((p) => p.age >= 18);
    // Result: allAdults = true
  3. map() and filter() with Objects

    You can use map() and filter() with arrays of objects in a similar way as with regular arrays. For example, to create a new array with the names of people under the age of 30:

    const youngNames = people.filter((p) => p.age < 30).map((p) => p.name);
    // Result: youngNames = ["Bob"]

These additional array methods, when combined with objects, provide powerful tools for working with complex data structures in JavaScript. Whether you’re dealing with simple arrays of primitive values or more complex arrays of objects, mastering these methods will make your code more efficient and maintainable.

Conclusion

JavaScript arrays and objects are fundamental data structures that allow developers to store and manipulate data effectively. Understanding their methods and how to use them is crucial for building robust and efficient applications. By mastering these concepts and methods, you’ll be well-equipped to work with arrays and objects in JavaScript and create dynamic and interactive web applications.