Array in javascript and Methods of Array

Array in javascript and Methods of Array

This article is all about what is an array, How to create array and methods of Array

Introduction

This post will explain how to interact with array data using array methods. You will learn about different methods and how they work. You will also see some examples of syntax and an explanation of the behavior. Finally, you will see some code examples of ways to use array methods in practical situations.

Let’s dive in. Are you ready?

1qlmai.jpg

What is Array means?

In JavaScript, an array is a single variable that is used to store different elements. It is often used when we want to store a list of elements and access them by a single variable. Each item in an array has a number attached to it, called a numeric index, that allows you to access it. In JavaScript, arrays start at index zero and can be manipulated with various methods.

ok not understood with theory download.jpg Here is the example

let myArray = [1, 2, 3, 4];
let catNamesArray = ["Hanuman", "Batman", "Autumn"];
//Arrays in JavaScript can hold different types of data, as shown above.

we can create Array in different ways images.jpg

Yes, I am sure and let's understand how to create that.

Ways To Create Javascript Arrays

There are Three ways to create an array.

1. Using array constructor

The Array() constructor is used to create Array objects.

let fruits= new Array()
let fruits=new Array(arrayLength)

Array constructor with a single parameter

Arrays can be created using a constructor with a single number parameter. An array with its length property set to that number and the array elements are empty slots.

const fruits = new Array(2);

console.log(fruits.length); // 2
console.log(fruits[0]);     // undefined

Array constructor with multiple parameters

If more than one argument is passed to the constructor, a new Array with the given elements is created.

const fruits = new Array('Apple', 'Banana');

console.log(fruits.length); // 2
console.log(fruits[0]);     // "Apple"

2. Using square brackets[ ] (or, Array Literal Notation)

Arrays can be created using literal notation. This is the most preferred way to create an array.

const fruits = ['Apple', 'Banana'];

console.log(fruits.length); // 2
console.log(fruits[0]);     // "Apple"

3. Using split

We can split a string at different positions and then change it to an array. Let's see the examples below:

let Blog = "Hashnode";
const blogArr = Blog.split("");
console.log(blogArr); // ['H', 'a', 's', 'h', 'n', 'o', 'd', 'e']

But wait it is not over there are so many methods of the array there.

download.jpg

So without any further delay let's get started to discuss Array methods.

Methods In Array

1. toString()

  • The JavaScript method toString() converts an array to a string of (comma separated) array values.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits.toString()) //Banana,Orange,Apple,Mango

2.length

  • The length method is used To know the size of an array
const fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits.length) //4

3.indexOf()

  • The IndexOf()method is used To check if an element exists in an array. If it exists, it returns the index of the element else returns -1.
let arr=['Amazon', 'Netflix', 'Uber']
console.log(arr.indexOf('Uber'))   //2

4.lastIndexOf()

  • It returns the index of the last element in the array, if it exists else returns -1
    let companies=['Amazon', 'Netflix', 'Uber','Apple']
    console.log(companies.lastIndexOf('Uber'))   //2
    console.log(companies.lastIndexOf('Infosys'))   //-1
    

5.pop()

  • The pop() method removes the last element from an array and returns that element.

  • Returns undefined if the array is empty.

This method changes the original array and its length.

let cities = ["Madrid", "New York", "Kathmandu", "Paris"];

// remove the last element
let removedCity = cities.pop();

console.log(cities)         // ["Madrid", "New York", "Kathmandu"]
console.log(removedCity);   // Paris

6.push()

  • The push() method adds zero or more elements to the end of the array.

This method changes the original array and its length.

let city = ["New York", "Madrid", "Kathmandu"];

// add "London" to the array
city.push("London");

console.log(city);

// Output: [ 'New York', 'Madrid', 'Kathmandu', 'London' ]

7. reduce()

  • The reduce() method executes a reducer function on each element of the array and returns a single output value.
const message = ["JavaScript ", "is ", "fun."];

// function to join each string elements
function joinStrings(accumulator, currentValue) {
  return accumulator + currentValue;
}

// reduce join each element of the string
let joinedString = message.reduce(joinStrings);
console.log(joinedString);

// Output: JavaScript is fun.

8.reverse()

  • The reverse() method returns the array in reverse order.
let numbers = [1, 2, 3, 4, 5];

// reversing the numbers array
let reversedArray = numbers.reverse();

console.log(reversedArray);

// Output: [ 5, 4, 3, 2, 1 ]

9.shift()

  • The shift() method removes the first element from an array and returns that element.
let Company= ["LCO", "Ineuron", "LCOPro", "Hashnode"];

// removes the first element of the array
let first = Company.shift();
console.log(first);
console.log(Company);

// Output: LCO
//         [ "Ineuron", "LCOPro", "Hashnode" ]

10.slice()

  • The slice()method returns a shallow copy of a portion of an array into a new array object.
let numbers = [2, 3, 5, 7, 11, 13, 17];

// create another array by slicing numbers from index 3 to 5
let newArray = numbers.slice(3, 6);
console.log(newArray);

// Output: [ 7, 11, 13 ]

11.some()

  • The some() method tests whether any of the array elements pass the given test function.
// a test function: returns an even number
function isEven(element) {
  return element % 2 === 0;
}

// defining an array
let numbers = [1, 3, 2, 5, 4];

// checks whether the numbers array contain at least one even number
console.log(numbers.some(isEven));

// Output: true

12.sort()

  • Thesort()method sorts the items of an array in a specific order (ascending or descending).
let city = ["California", "Barcelona", "Paris", "Kathmandu"];

// sort the city array in ascending order
let sortedArray = city.sort();
console.log(sortedArray);

// Output: [ 'Barcelona', 'California', 'Kathmandu', 'Paris' ]

There are too many methods of Array in javascript But that's enough for this article😁😁

download.jpg

conclusion

A quick recap of the article. We understand what is Array, how to create an array, and the Methods of Array. I hope that this article is useful to you, to help understand the topic better. If you have any questions, you can leave them in the comments section below.

Happy Coding.

ByBy

Follow Me

images.jpg