Array operations in DSA JavaScript
You will find array operations in JavaScript here
// Insertion - insert an element at the begining of array
function InsertAtBegining(arr,element){
// move all the elements from last to one position next to create an empty space at the begining for insertion
for(let i =arr.length-1; i>=0; i--){
arr[i+1] = arr[i];
if(i==0){
// Now insert at the empty space in the begining
arr[i] = element;
}
}
return arr;
}
// Insertion - Insert an element the end of the array
function InsertAtEndOfArray(arr, element){
arr[arr.length]= element;
return arr;
}
// Insertion - Insert an element at a given index in an array
function insertAtGivenIndex(arr,index,element){
for(let i =arr.length; i>=index-1; i--){
arr[i+1] = arr[i];
}
arr[index-1] = element;
return arr;
}
// Deletion - Delete an element at a given index in an array
function DeleteAnElement(arr,index){
for(let i=index-1; i<arr.length-1; i++){
arr[i]= arr[i+1];
}
return arr;
}
// Search − Searches an element using the given index or by the value.
function searchElement(arr,value){
for(let i=0; i<=arr.length; i++){
if(arr[i]==value){
return i;
}
}
return false;
}
// Update − Updates an element at the given index.
function udpateElement(arr,index,value){
for(let i=0; i<=arr.length; i++){
if(i==index-1){
arr[i]= value;
}
}
return arr;
}
// Traverse − print all the array elements one by one.
function TraverseArray(arr){
for(let i=0; i<=arr.length; i++){
console.log(arr[i]);
}
}
let arr =[2,1,22,1,4,5,5,6];
//let result1= InsertAtBegining(arr,10);
//console.log(result1);
//let result2= InsertAtEndOfArray(arr, 20);
//console.log(result2);
//let result3 = insertAtGivenIndex(arr,8,300);
//console.log(result3);
//let deleteEle = DeleteAnElement(arr,3);
//console.log(deleteEle);
//let searchEle = searchElement(arr,300);
//console.log(searchEle);
//let updateEle= udpateElement(arr,3,33);
//console.log(updateEle)
//TraverseArray(arr);