0

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]
1

2 Answers 2

2
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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

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

1 Comment

but here sir i cant add more than one items

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.