2

I am generating an array like :

const myArray = Array.from({length: 5}, (e, i) => emptyX)

myArray starts with 5 elements of emptyX.

Is there a simple way/method which unshift the array without changing its size ? Whenever I call it I must find the initial size.

exemple:

myArray.unshift(X1) => [X1, emptyX, emptyX, emptyX, emptyX]
myArray.unshift(X2) => [X2, X1, emptyX, emptyX, emptyX]
myArray.unshift(X3) => [X3, X2, X1, emptyX, emptyX]

// OR with multiple parameters
myArray.unshift(X4, X5) => [X5, X4, X3, X2, X1]

UPDATE:

Now I am doing :

myArray.unshift(X);
myArray.splice(-1, 1);// or pop()

But it's not what I want, I need just to replace the items because the array size change when I call unshift and splice

7
  • 1
    What would it mean to .unshift() an element from the array without changing the array size O.o? Commented Jul 24, 2019 at 14:41
  • Wait can't you modify myArray[0] etc? Like, myArray[0] = X1;? Commented Jul 24, 2019 at 14:42
  • 2
    myArray[0] = X1? Commented Jul 24, 2019 at 14:42
  • yes for myArray[0] = X1, but i have to move the other elements to the right Commented Jul 24, 2019 at 14:46
  • What is emptyX ? Is it null ? undefined ? What is supposed to happen when we unshift X2 to [empty, X1] ? Commented Jul 24, 2019 at 14:46

5 Answers 5

3

You are looking for the ShiftRight method which is unavailable in the prototype. Here is a pollyfill:

Array.prototype.shiftRight = function(...params) {
   
    params.forEach(item => {
        for (var i = this.length - 1; i >= 0; i--) {
            if (i === 0)
               this[0] = item
            else
               this[i] = this[i - 1];
        }
    })
}


x = [1, 2, 3];

x.shiftRight(4, 5);

console.log(x);   // [5, 4, 1]

Sign up to request clarification or add additional context in comments.

6 Comments

goood & simple, but the last element must be 1 not 3,
This is a nicer approach than mine but the "0" iteration and check is unneeded. You can combine my answer with this ^^
As per OP, the length of the array cannot be changed during the operation. That is wjy I didn't use unshift.
Yes, I don't use unshift either
Ya sure. I mistook the name of your function. However your solution doesn't cover multiple elements being inserted at the beginning of the array.
|
1

You could do something like this-

class arrWrapper(myArray: Array) {
    this.arr = myArray;
    this.len = myArray.length;
    this.pos = 0;

    unshift(newObj) {
       //Add checks if lengeh > pos, do something - either return or pos = 0
       this.arr[this.pos++] = newObj;
    } 
}

After comments I realize what you tried to do. This will "shift" the items up, without removing them:

class arrWrapper(myArray: Array) {
    this.arr = myArray;

    unshift(newObj) {
       for (i=1; i<this.arr.length-1; i++) {
          this.arr[i] = this.arr[i-1];
       } 
       this.arr[0] = newObj;
    } 
}

this will run on the array, shift the cells up, and always insert the newObj into the first position

Another edit: oh sry, I didn't test it, you should go backwards to avoid the same item shift

Example with test:

function unshift(arr, newObj) {
           for (i=arr.length-1; i>0; i--) {
              arr[i] = arr[i-1];
           } 
           arr[0] = newObj;
        } 
        
var testArr= [1,2,3,4];

unshift(testArr, "new1");
console.log(testArr);

unshift(testArr, "new2");
console.log(testArr);

unshift(testArr, "new3");
console.log(testArr);

unshift(testArr, "new4");
console.log(testArr);

4 Comments

good but the resulat will be [X5, X4, X3, X2, X1].reverse() i think
no, because you start from pos = 0, you could do pos = length and then --pos
the last inserted element must occupy the 0 position, the old one must unshift to the right (and keeping there order)
have you test it ? I think this will copy the first element to all elements of the array. You copy 0 in 1, 1 in 2, but 1 is 0 now and so on
1

You can simplify your answer by using the Array.prototype.unshift and Array.prototype.pop methods, like this:

myArray.unshift()
myArray.pop();

The unshift method adds one or more elements to the beginning of an array and returns the new length of the array.

And the pop method removes the last element from an array and returns that element (this method changes the length of the array).

1 Comment

Though this answers the question, you should explain your answer, what each function does, and why it solves the problem
0

Try this :

const myArray = Array.from({length: 5}, (e, i) => "emptyX")
//with multiple parameters
var items=[1,2,3,4];

doUnshift(myArray,items);


function doUnshift(myArray,items){
 
    var l=myArray.length;
    //myArray size must be greater than items array size
    if(l<=myArray.length){
    items.reverse();
    for(var i=0;i<items.length;i++){
      myArray.unshift(items[i])
    }
    myArray.splice(items.length,items.length)
      console.log(myArray)
   } else{
         console.log("myArray size must be greater than items array size")  
   }
    
    
}

3 Comments

i am already doing the same thing (with only one element), check after the UPDATE section
this code run with only one element, just change var items=[1];
yes of course, your solution is more elaborated than mine
0

A simple way to do it is

const myArray=[1, 2]

const newValue=3

myArray.unshift(newValue)
myArray.length = 5

console.log(myArray)

You are allowed to truncate, and extend an array by setting the length manually.

So in this case, if you only had 2 items in the array, and set it to 5, you would get 2 element and 3 undefined elements.

More details here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length

If you are using this in a reactive framework like Vue, switch the lines around because unshift will be handled by the framework to trigger an update.

const myArray=[1, 2, 3, 4, 5]

const newValue=6

myArray.length = 4 // drop to 4, some frameworks miss this change
myArray.unshift(newValue) // add back in the 5th option

console.log(myArray)

A handy side effect of this version is, from an outside view, the size of the array never changed. If something is monitoring unshift, then it thinks there is 5 elements, you manually truncated, then unshifted to 5 elements again. Therefore no change in size has taken place.

Comments

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.