0

I have an Array like

var myArray = new Array;

I have to push some elements to array in such a way that the elements will be replaced with same index.

Example :

myArray.push(1);
myArray.push(2);
myArray.push(3);

so now

myArray[0] = 1
myArray[1] = 2

now when i will push element 3 then myArray[0] will be replaced with 3 and myArray[1] will be replaced with 1 and the element 2 will be removed.

It will continue according to the number of elements pushed...

Can any body help me with this requirement...

2 Answers2

0

push adds to the end of an array. If you want to add a value to the beginning of an array you can use unshift.

myArray.unshift(3);

You can then use pop to remove the last element:

arr.pop();

DEMO

However, what you might need, given that you need to remove the same number of elements from an array that you add is a function that uses concat and slice instead:

function pusher(arr, add) {
  return add.concat(arr).slice(0, arr.length);
}

var arr = [1, 2, 3, 4];
var arr = pusher(arr, [5, 6]); // [5, 6, 1, 2]

DEMO

Andy
  • 61,948
  • 13
  • 68
  • 95
0

I think you need something in the lines of:

myArray.unshift(element);
myArray.pop();

Explanation:

  • unshift: inserts the element on position 0 and moves all other elements one position to the right
  • pop: removes last element from array
Octav Zlatior
  • 451
  • 4
  • 14