Array Methods in JavaScript That Every Developer Should Know

IN DEPTH OF ARRAY METHODS.

Array Methods in JavaScript That Every Developer Should Know

Greetings everyone! I hope everything is going well for you. Today's blog will explain JavaScript arrays, or more specifically, the most useful array techniques that every developer should be familiar with 😜. For those who are unfamiliar with or haven't worked with JavaScript arrays in a while, let's first define an array before moving on.

In JavaScript, an object called an array is used to bring together numerous values of the same or distinct data types. Therefore, we are able to store items of the types Number, Boolean, String, Object, etc.

Two square brackets [] are used to denote an array. Elements are the values contained in an array, and index determines where they are located ( or indices). In an array, commas are used to separate each element (,).

Arrays

In terms of programming, an array is referred to as a group of elements or objects. Data is stored in elements that can be retrieved whenever necessary. In the computer languages that allow it, it is a frequently used data structure. A pair of square brackets [] can be used to symbolise an array in JavaScript. The array's elements are all separated by commas (,). You can create an array with elements of data type String, Boolean, Number, Objects, and even other Arrays. They can be a collection of elements of any data type. In a single variable, they are used to store several values.

Syntax:

const array_name = [itemA, itemB, itemC,.............];

Sample Example

 const name = ["Hitesh Sir", "Anurag Sir", "Anirudh sir"];
 console.log(name);

Output

Hitesh Sir  Anurag Sir  Anirudh sir

In JavaScript, arrays are quite amazing πŸ˜„.

How to Access the Elements of an Array:

The index of an array can be used to retrieve its components.

const groceryList= [ 'egg', 'butter', 'bread', 'cereals', 'rice' ];
groceryList[0];        //egg
groceryList[1];        //butter
groceryList[2];        //bread
groceryList[3];        //cereals
groceryList[4];        //rice

Array Methods in JavaScript

1. push()

Add one or more elements to the array's end.

> const names = ["Hitesh Sir", "Anurag Sir"];
> names.push("Brijesh"); 
> // ["Hitesh Sir", "Anurag Sir", "Brijesh"]

image1.jpg

2. pop()

Returns the element that was the last in the array after it is removed.

const numbers = [10,20,30,40];
const ele = numbers.pop(); 

//numbers = [10,20,30]

image3.jpg

3. shift()

The array's first element is shifted (removed), and the shifted element is then returned.

const marks = [99,79,70,80]; 
const first = marks.shift(); 

//marks = [79, 70, 80]

image1-1.jpg

4. unshift()

Adds one or more elements to the array's starting point.

const marks = [99,79,70,80];
marks.unshift(74,87); 
//[74, 87, 99, 79, 70, 80]

image3-2.jpg

5. concat()

Combines multiple existing arrays to create a single new array.

 const one = [1,2,3];
 const two = [2,4,6];
 const three = [3,6,9,12];

const newArray = one.concat(two,three);  
//[1, 2, 3, 2, 4, 6, 3, 6, 9, 12]

6. toString()

Returns a string that is made up of the array's elements. doesn't alter the initial array in any way. excludes all parameters.

const arr = ['she', 'got', 100, 'marks'];
const str = arr.toString(); 
//'she,got,100,marks'

7. join()

Returns a string that is made up of the array's elements. doesn't alter the initial array in any way. We can define a separator here.

const arr = ['she', 'got', 100, 'marks'];
const str = arr.join(' '); 
//'she got 100 marks'
const str1 = arr.join(' # '); 
//'she # got # 100 # marks'

8. slice()

It gives back a copy of a specific area of the original array. The initial array is unaltered. It starts copying (slicing) from start to end and has two optional parameters: start and end. In this case, the end is final. Start has a default value of 0, thus if start is not specified, it will take that value by default.

//arr.slice(start,end); --> Syntax
const arr = ['priya', 'pankaj', 'rohan', 'Diksha']; 
const newArr = arr.slice(1,3); 

//arr = ['priya', 'pankaj', 'rohan', 'Diksha']
//newArr = ['pankaj', 'rohan']

slice-example-1.gif

9. splice()

Adds/removes array elements and returns an array of deleted items.

const arr = ['priya', 'pankaj', 'rohan'];
const newArr = arr.splice(1,1,'gourav','vishal');
//arr ['priya', 'gourav', 'vishal', 'rohan']
//newArr  ['pankaj']

JavaScript-Array-Splice-Delete-Example.png

10. reverse()

Reverse the order of the elements in the array.

const numbers = [5,10,15,20];
numbers.reverse(); 
//[20, 15, 10, 5]

11. sort()

Sorts the array's elements alphabetically. Sorting involves placing the components in either ascending or descending order.

//Array.sort()
const arr = [100,21,3,120,1000,1];
arr.sort();
console.log(arr);
//[1, 100, 1000, 120, 21, 3]

12. includes()

Determines if a given value is present in an array. if it includes, returns true; if not, returns false.

//  Array.includes(searchValue,start);
const arr = [10,20,30,40];

let result = arr.includes(20); 
console.log(result); //true

result = arr.includes(20,2);
console.log(result); //false

13. indexOf()

Provides the index of a value's first appearance in the array. If the value cannot be found, -1 is returned.

// Array.indexOf(searchValue,start);
const arr = [10,20,30,20,40];

let result = arr.indexOf(20);
console.log(result); 
 // 1

result = arr.indexOf(10,1);
console.log(result);  
// -1

demo-3.gif

14. lastIndexOf()

Provides the index of a value's last appearance in the array. If the value cannot be found, -1 is returned.

// Array.lastIndexOf(searchValue, start);
const arr = [10,20,30,20,40];

result = arr.lastIndexOf(20,2);
console.log(result);  
// 1

result = arr.lastIndexOf(40,3);
console.log(result);  
// -1

15. find()

Returns the first element that satisfies the function's initialised condition.

const arr = [10,20,30,40];
let result = arr.find( ele => ele > 25);
console.log(result);  
//30

result = arr.find( ele => ele < 10);
console.log(result); 
 //undefined

16. findIndex()

Identifies the index of the first element that meets the function's implementation of the provided criteria.

const arr = [10,20,30,40];
let result = arr.findIndex( ele => ele > 25);
console.log(result); 
 //2

result = arr.findIndex( ele => ele < 10);
console.log(result); 
 //-1

17. every()

Determines whether each array element has passed the function's test.

const count = [12,45,65,23,47,89];

let result = count.every((ele)=> ele > 10);
console.log(result);  
//true

result = count.every((ele)=> ele > 20);
console.log(result); 
 //false

18. map()

In contrast to forEach(), it creates a new array by invoking the specified function on each element of the original array rather than altering the existing array.

/*Array.map(function(currElement, index, arr){ 
    //code
});*/

let marks = [79,98,95,60];

let updatedMarks = marks.map(function(curr){
    return curr + 10;
});

console.log(marks); 
//[79, 98, 95, 60]
console.log(updatedMarks);
 //[89, 108, 105, 70]



updatedMarks = marks.map(myFun);

function myFun(ele){
    ele = ele - 5; 
    return ele;
}

console.log(marks); 
//[79, 98, 95, 60]
console.log(updatedMarks); 
//[74, 93, 90, 55]

1_4EGwsCicbWJeml2aAm714A.gif

19. filter()

It generates a new array with the elements that satisfy the function's requirement. The initial array is unaltered.

/*Array.filter(function(currElement, index, arr){ 
    //condition
});*/
let marks = [79,98,95,60];

let toppers = marks.filter(curr => {
    return curr > 80;
});

console.log(marks);
 //[79, 98, 95, 60]
console.log(toppers); 
//[98, 95]

20. reduce()

Reduce() makes a call to or runs the function on each element of the array and outputs a single value (the function's aggregated result).

/*Array.reduce( function ( accumulator,   currentElement ) 
{ operation }, initialValue )*/

const maxValue = arr.reduce( (max, curr) => {
    if(curr > max)
    {
        max = curr;
    }
    return max;
}, 0);
console.log(maxValue); 
 // 50

Arrays in JavaScript have a tonne of helpful methods that can streamline our development processes. Knowing these techniques can help us save time and perhaps improve the efficiency of our programming. I sincerely hoped that everyone learnt something today, whether it was new array ways or reviewing earlier concepts that they may apply to their upcoming projects.

THANK YOU FOR READING.png

Β