简体   繁体   中英

Javascript : unshift without modifing the array size

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

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]

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);

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).

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") } }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM