Skip to content

Latest commit

 

History

History
317 lines (221 loc) · 8.8 KB

File metadata and controls

317 lines (221 loc) · 8.8 KB

JavaScript Array

In JavaScript, an array is a built-in data structure that allows you to store and manipulate a collection of elements, which can be of different types (e.g., numbers, strings, objects). Arrays are one of the most commonly used data structures and provide powerful methods for working with collections of data. Here's an overview of JavaScript arrays:

Creating Arrays

You can create arrays in JavaScript in various ways:

1. Array Literal Notation

The simplest way to create an array is to use array literal notation with square brackets:

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

2. Array Constructor

You can also create an array using the Array constructor:

const colors = new Array("red", "green", "blue");

3. Array Elements

Arrays can contain elements of different types, including numbers, strings, objects, or even other arrays:

const mixedArray = [1, "apple", { name: "John" }, [2, 3, 4]];

Accessing Array Elements

You can access array elements by their index, with the first element at index 0:

const fruits = ["apple", "banana", "cherry"];
const firstFruit = fruits[0]; // "apple"
const secondFruit = fruits[1]; // "banana"

Modifying Array Elements

You can modify array elements by assigning new values to specific indexes:

fruits[2] = "orange"; // Modifies the third element to "orange"

Array Properties and Methods

JavaScript arrays come with various built-in properties and methods:

Array Length Property

The length property returns the number of elements in an array:

const numbers = [1, 2, 3, 4, 5];
const length = numbers.length; // 5

Array Methods

JavaScript arrays have many useful methods for manipulation, including:

  • push(): Adds elements to the end of an array.

  • pop(): Removes the last element from the end of an array.

  • unshift(): Adds elements to the beginning of an array.

  • shift(): Removes the first element from the beginning of an array.

  • concat(): Combines two or more arrays.

  • slice(): Creates a new array from a portion of an existing array.

  • splice(): Adds or removes elements at a specific index in the array.

  • join(): Converts an array into a string with specified separators.

  • indexOf(): Returns the index of the first occurrence of a specified element.

  • lastIndexOf(): Returns the index of the last occurrence of a specified element.

  • forEach(): Iterates over each element in the array.

  • map(): Creates a new array with the results of applying a function to each element.

  • filter(): Creates a new array with elements that satisfy a condition.

  • reduce(): Reduces an array to a single value by applying a function cumulatively.

  • sort(): Sorts the elements in the array (in place by default).

  • reverse(): Reverses the order of the elements in the array.

  • find(): Returns the first element in the array that satisfies a condition.

  • findIndex(): Returns the index of the first element that satisfies a condition.

  • includes(): Checks if an array contains a specified element.

Examples for each of these methods :

  1. push(): Adds elements to the end of an array.

    const fruits = ["apple", "banana"];
    fruits.push("cherry");
    // fruits is now ["apple", "banana", "cherry"]
  2. pop(): Removes the last element from the end of an array.

    const fruits = ["apple", "banana", "cherry"];
    fruits.pop();
    // fruits is now ["apple", "banana"]
  3. unshift(): Adds elements to the beginning of an array.

    const fruits = ["banana", "cherry"];
    fruits.unshift("apple");
    // fruits is now ["apple", "banana", "cherry"]
  4. shift(): Removes the first element from the beginning of an array.

    const fruits = ["apple", "banana", "cherry"];
    fruits.shift();
    // fruits is now ["banana", "cherry"]
  5. concat(): Combines two or more arrays.

    const fruits = ["apple", "banana"];
    const vegetables = ["carrot", "broccoli"];
    const combined = fruits.concat(vegetables);
    // combined is ["apple", "banana", "carrot", "broccoli"]
  6. slice(): Creates a new array from a portion of an existing array.

    const fruits = ["apple", "banana", "cherry", "date"];
    const sliced = fruits.slice(1, 3);
    // sliced is ["banana", "cherry"]
  7. splice(): Adds or removes elements at a specific index in the array.

    const fruits = ["apple", "banana", "cherry"];
    fruits.splice(1, 1, "kiwi", "mango");
    // fruits is now ["apple", "kiwi", "mango", "cherry"]
  8. join(): Converts an array into a string with specified separators.

    const fruits = ["apple", "banana", "cherry"];
    const joined = fruits.join(", ");
    // joined is "apple, banana, cherry"
  9. indexOf(): Returns the index of the first occurrence of a specified element.

    const fruits = ["apple", "banana", "cherry"];
    const index = fruits.indexOf("banana"); // index is 1
  10. lastIndexOf(): Returns the index of the last occurrence of a specified element.

    const fruits = ["apple", "banana", "cherry", "banana"];
    const index = fruits.lastIndexOf("banana"); // index is 3
  11. forEach(): Iterates over each element in the array.

    const numbers = [1, 2, 3];
    numbers.forEach(function(number) {
        console.log(number);
    });
    // Outputs: 1, 2, 3
  12. map(): Creates a new array with the results of applying a function to each element.

    const numbers = [1, 2, 3];
    const squared = numbers.map(function(number) {
        return number * number;
    });
    // squared is [1, 4, 9]
  13. filter(): Creates a new array with elements that satisfy a condition.

    const numbers = [1, 2, 3, 4, 5];
    const evenNumbers = numbers.filter(function(number) {
        return number % 2 === 0;
    });
    // evenNumbers is [2, 4]
  14. reduce(): Reduces an array to a single value by applying a function cumulatively.

    const numbers = [1, 2, 3, 4, 5];
    const sum = numbers.reduce(function(accumulator, currentValue) {
        return accumulator + currentValue;
    }, 0);
    // sum is 15
  15. sort(): Sorts the elements in the array (in place by default).

    const fruits = ["cherry", "banana", "apple"];
    fruits.sort();
    // fruits is now ["apple", "banana", "cherry"]
  16. reverse(): Reverses the order of the elements in the array.

    const numbers = [1, 2, 3, 4, 5];
    numbers.reverse();
    // numbers is now [5, 4, 3, 2, 1]
  17. find(): Returns the first element in the array that satisfies a condition.

    const numbers = [1, 3, 5, 7, 9];
    const evenNumber = numbers.find(function(number) {
        return number % 2 === 0;
    });
    // evenNumber is 3
  18. findIndex(): Returns the index of the first element that satisfies a condition.

    const numbers = [1, 3, 5, 7, 9];
    const index = numbers.findIndex(function(number) {
        return number % 2 === 0;
    });
    // index is 1
  19. includes(): Checks if an array contains a specified element.

    const fruits = ["apple", "banana", "cherry"];
    const containsBanana = fruits.includes("banana"); // containsBanana is true

These methods are essential for working with arrays in JavaScript, allowing you to perform various operations and transformations on array data efficiently.

These are just a few examples of the methods available for manipulating arrays in JavaScript. Arrays are a versatile and fundamental data structure used in a wide range of programming scenarios, from simple data storage to complex data processing.


Assignment and Task

Create an array named greet with values 'hello', 'hi'. Find the length of an array. Add the new element 'welcome' to the array. Find the new length of an array.

Solution:

const greet = ['hello', 'hi'];
const greetLength = greet.length;
console.log(greetLength);
greet.push('welcome');
const addGreetLength = greet.length;
console.log(addGreetLength);

Output

2
3

p4n Quiz

Q. What is the output of the program?

let routine = [ 'eat', 'sleep'];
routine.push('exercise');
routine[4] = 'work';
console.log(routine[3]);
  1. Error
  2. exercise
  3. undefined
  4. work

Answer: 3