24
JavaScript Array Methods.
Hello Everyone
In This Article We Will be Seeing Different Array Methods.
Follow Me on LinkedIn https://www.linkedin.com/in/ajaysharma12799/
Follow Me on Github https://www.github.com/ajaysharma12799/
Create Array Either Using Square Braces or Using new Array() Class
let arr = [1,2,3,4,5];
let arr = new Array(length or element);
arr.push(10); // Insert Element at Last of Array
arr.pop(); // Remove Last Element of Array and Return It
arr.shift(); // Remove First Element of Array and Return It
arr.unshift(20); // Insert Element at First Position in Array
arr.length; // Return Length of Array
arr.fill(0); // Fill Entire Array With 0 or with Given Item
let arr1 = [1,2,3];
let newArray=arr1.concat([4,5,6]); // O/P = [1,2,3,4,5,6]
let arr2 = [1,2];
let newArray=arr2.concat([4,5], [7,8]); // O/P = [1,2,4,5,7,8]
let arr = [1,2,3,4,5];
let found = arr.find(element => element > 2);
console.log(found); // O/P = 3
9. findIndex() (Take a Function Which Execute and Return First Value Index Which Satisfies Condition)
let arr = [1,2,3,4,5];
let found = arr.findIndex(element => element > 2);
console.log(found); // O/P = 2
let arr = [1,3,2,4,6];
arr.sort();
console.log(arr); // O/P = [1,2,3,4,6]
Note:- But This Method Will Not Sort Value Which is of 2 Digit, So We Need to Make Our Custom Function and Pass into Sort Method.
let arr = [1,4,2,45,6,7];
arr.sort((a,b) => a-b); // Change a or b according to you if you want in Ascending or Descending Order.
console.log(arr); // O/P = [1,2,4,6,7,45];
let arr = [1,5,2,4,3];
let reversedArray = arr.reverse();
// Reverse Array and return Reference to Same Array
console.log(reversedArray); // O/P = [5,4,3,2,1]
start => Starting Index From 0 and It is Included
end => Ending Index Which is Length - 1 and It is Not Included
let arr = [1,2,3,4,5];
let slicedArray = arr.slice(0,3);
console.log(slicedArray); // O/P = [1,2,3]
13. splice(start, deleteCount: Optional, element: Optional) ( Remove Element From Array and Can Also Insert New Elements In the Place of Removed Element )
let arr = [1,2,3,4,5];
let splicedArray1 = arr.splice(2);
console.log(splicedArray1);
/*
Will Remove Array Element From Index 2 to End and Return in Form of Array.
O/P = [3,4,5]
*/
let splicedArray2 = arr.splice(2, 2 10, 30);
console.log(splicedArray2);
/*
Will Remove Array Element From Index 2 to End and Return in Form of Array.
O/P = [3, 4] // Spliced Array
O/P = [1,2,10,30,5] // Original Array After Inserting New Element InPlace of Removed Element.
*/
let arr = [1,2,3,4,5];
console.log(arr.indexOf(5)); // O/P = 4
15. includes(element, startIndex: Optional) ( Search For Given Element If Found Return True Otherwise False )
let arr = [1,2,3,4,5];
console.log(arr.includes(5)); // O/P = true
console.log(arr.includes(2, 3)); // O/P = false, Because We Are Searching From Index 3 and 2 is Not Present in Array From Index 3.
24