DEV Community

Abinaya V
Abinaya V

Posted on

METHODS OF ARRAY

A method in an array (JavaScript) is simply a built-in function that works on arrays.
It helps you add, remove, search, or modify elements inside an array.

What is an Array Method?

    An array method is a function attached to an array object.
Enter fullscreen mode Exit fullscreen mode

Example:

  let fruits = ["apple", "banana", "mango"];

  fruits.push("orange"); // push() is a method

  console.log(fruits);
Enter fullscreen mode Exit fullscreen mode

basic Array Methods

1. push() → Add element at end

    let arr = [1, 2, 3];
    arr.push(4);
    console.log(arr); // [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

2. pop() → Remove last element

     let arr = [1, 2, 3];
     arr.pop();
     console.log(arr); // [1, 2]
Enter fullscreen mode Exit fullscreen mode

3. shift() → Remove first element

    let arr = [1, 2, 3];
    arr.shift();
    console.log(arr); // [2, 3]
Enter fullscreen mode Exit fullscreen mode

4. unshift() → Add element at beginning

   let arr = [1, 2, 3];
   arr.unshift(0);
   console.log(arr); // [0, 1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

5. length → Find size of array

 let arr = [10, 20, 30];
 console.log(arr.length); // 3
Enter fullscreen mode Exit fullscreen mode

6. indexOf() → Find position

  let arr = ["a", "b", "c"];
  console.log(arr.indexOf("b")); // 1
Enter fullscreen mode Exit fullscreen mode

7. includes() → Check value exists

 let arr = [1, 2, 3];
 console.log(arr.includes(2)); // true
Enter fullscreen mode Exit fullscreen mode

8. slice() → Get part of array

 let arr = [1, 2, 3, 4];
 console.log(arr.slice(1, 3)); // [2, 3]
Enter fullscreen mode Exit fullscreen mode

9. splice() → Add/Remove elements

 let arr = [1, 2, 3];
 arr.splice(1, 1); // remove 1 element at index 1
 console.log(arr); // [1, 3]
Enter fullscreen mode Exit fullscreen mode

10. forEach() → Loop through array

let arr = [1, 2, 3];
arr.forEach(function(num) {
console.log(num);
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)