Hello amazing people, Today we are going to discuss Javascript array methods.
I have divided this topic into three parts. And This is part 1.
Let's start!
1. push()
Add one or more elements to the end of the array.
//push()
//adding a single element
const names = ['Diksha', 'Anjali'];
names.push('Rahul');
// ['Diksha', 'Anjali', 'Rahul']
//Adding multiple elements
const colors = ['blue','green'];
colors.push('red','purple','pink');
// ['blue', 'green', 'red', 'purple', 'pink']
2. pop()
Removes the last element from the array and returns that element.
//pop()
const numbers = [10,20,30,40];
const ele = numbers.pop();
//numbers = [10,20,30]
//ele = 40
3. shift()
Shift (remove) the first element of the array and return that shifted element.
//shift()
const marks = [99,79,70,80];
const first = marks.shift();
//marks = [79, 70, 80]
//first = 99
4. unshift()
Adds one or more elements to the beginning of the array.
//unshift()
const marks = [99,79,70,80];
marks.unshift(74,87); //[74, 87, 99, 79, 70, 80]
5. concat()
Creates a new array by concatenating already existing arrays.
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 formed by the elements of the array.
Does not change the original array.
Does not take any parameters.
//toString()
const arr = ['she', 'got', 100, 'marks'];
const str = arr.toString(); //'she,got,100,marks'
7. join()
Returns a string formed by the elements of the array.
Does not change the original array.
Here, We can specify the separator.
//join
const arr = ['she', 'got', 100, 'marks'];
const str = arr.join(' '); //'she got 100 marks'
const str1 = arr.join(' # '); //'she # got # 100 # marks'
8. slice()
Syntax:
arr.slice(start,end);
Returns the copy of a portion of the original array. It does not change the original array.
It has two parameters(optional) start and end, it starts copying(slicing) from start to end. Here, the end is exclusive.
The default value of start is 0, which means if start is not provided then it will take 0 by default.
//slice()
const arr = ['priya', 'pankaj', 'rohan', 'Diksha'];
const newArr = arr.slice(1,3);
//arr = ['priya', 'pankaj', 'rohan', 'Diksha']
//newArr = ['pankaj', 'rohan']
9. splice()
Adds/removes array elements and returns an array of deleted items.
//splice
const arr = ['priya', 'pankaj', 'rohan'];
const newArr = arr.splice(1,1,'gourav','vishal');
//arr -> ['priya', 'gourav', 'vishal', 'rohan']
//newArr -> ['pankaj']
Here, the first parameter contains the index from where the new elements should be added. The second parameter contains the number of elements that should be removed. And the rest of the parameters define the new elements to be added to the array.
10. reverse()
Reverse the order of the elements in the array.
/*reverse()*/
const numbers = [5,10,15,20];
numbers.reverse(); /*[20, 15, 10, 5]*/
Thanks for reading the blog.
Here is part 2.