JS Array Methods
- Pop- This method is used to remove the last element of the array.
Syntax
Array.pop()
let Courses = [“Php”, “java”, “c”];
alert( Courses.pop() );
alert( Courses);
- Push- This method is used to insert an element to the end of array.
Syntax
Array.push(‘element’)
let Courses = [“Php”, “java”, “c”];
Courses.push(“c++”) ;
alert( Courses);
- Shift- This method is used to remove the first element of the array.
Syntax
Array.shift()
let Courses = [“Php”, “java”, “c”];
alert( Courses.shift() );
alert( Courses);
- Unshift- This method is used to insert first element from an array.
Syntax
Array.unshift(‘element’)
let Courses = [“Php”, “java”, “c”];
Courses. unshift (“c++”) ;
alert( Courses);
- Splice- This method is used to add or remove elements from any index
Syntax
array.splice(index, howmany, item1, ….., itemX)
howmany is optional if 0 means no items is removed
let Courses = [“Php”, “java”, “c”];
var removed = Courses.splice(1,1);
alert( removed);
let Courses = [“Php”, “java”, “c”];
var removed = Courses.splice(1,0.”dotnet”);
alert( removed);
- Join- This method is used to join the elements of an array and create a string
Syntax
array.join(“” || ”,” || “-”)
let Courses = [“Php”, “java”, “c”];
var string = Courses.join();
alert( string);
- Slice- This method is used to extract the portion of an aaray
Syntax
array.slice(startIndex, endIndex)
let Courses = [“Php”, “java”, “c”];
var extract = Courses.slice(1);
alert( extract);
- Concat- This method is used to merge or combine two or more arrays
Syntax
Array.concat(array2)
let Courses = [“Php”, “java”, “c”];
let db = [“mysql”, “oracle”, “file”];
var result = Courses.concat(db);
alert( result);
- Sort- This method is used to sort the elements of an array
Syntax
Array.sort()
let Courses = [“Php”, “java”, “c”];
Courses.sort();
alert( Courses);