Home > Enterprise >  How To implement unshift method in Javascript
How To implement unshift method in Javascript

Time:12-06

i need make function like this:

Function add(arr,...newVal){

}

array = [1,2,3];
add(array,0)
console.log(array);        //i need here to print [0,1,2,3]

iam make function as push like that:

Function add(arr,...newVal){
for(var i=0; i<arr.length; i  ){
arr[arr.length]=newVal[i];
}return arr.length;
}

array = [1,2,3];
add(array,4)
console.log(array);        // here to print [1,2,3,4]

CodePudding user response:

const unshift = (arr, ...newVal) => {
    let i= arr.length   newVal.length -1;
    for( i ; i >= newVal.length; i--) {
        arr[i] = arr[i - newVal.length ];
    }

    for(i; i >= 0; i--) {
        arr[i] = newVal[i];
    }
    return arr;
}

CodePudding user response:

Try this:

const unshift = (arr, newVal) => {
    for(let i = arr.length; i > 0; i--) {
        arr[i] = arr[i - 1];
    }
    arr[0] = newVal;
    return arr;
}
  • Related