1

I have an array and i'm trying to push a object on specific length like on zero index position but it is pushing on last of the array length.

this.tradingPartner = new TradingPartnerModel();
this.tradingPartners = [...this.tradingPartners, this.tradingPartner];
ER.SHASHI TIWARI
  • 917
  • 1
  • 10
  • 25
  • https://stackoverflow.com/questions/586182/how-to-insert-an-item-into-an-array-at-a-specific-index – Oliver Cooke Sep 29 '17 at 12:10
  • plz clarify what you want to do ? If value present at particular index already then it will be replace with the new value. if you want to perform such operation then you can directly assign the value to particular index array[index] = value. – Shivam Sep 29 '17 at 12:10
  • just want to push a object on zero length of array using this new spared operator because i'm using latest primeng datatable and this is only support spared operator push in array. – ER.SHASHI TIWARI Sep 29 '17 at 12:13

3 Answers3

3

If you want to add an Object at specific place on array you should user 'splice' method, for example:

this.tradingPartner.splice(2, 0, this.tradingPartner);

will insert new Object at index 2

EDIT

If you want to add new element at start of current array using spread you should only reverse order:

this.tradingPartners = [this.tradingPartner, ...this.tradingPartners];
porgo
  • 1,729
  • 2
  • 17
  • 26
  • just want to push a object on zero length of array using this new spared operator because i'm using latest primeng datatable and this is only support spared operator push in array. – ER.SHASHI TIWARI Sep 29 '17 at 12:14
  • @ER.SHASHITIWARI i made an edit to my answer, chreck it – porgo Sep 29 '17 at 12:18
1

Use splice

this.tradingPartners.splice(index,0,item);

index = on which you want to add item = you want to add


pushdata(index,array,item)
{
let temp = [];
for(let i = 0; i< array.length ; i ++) {
if(i === index) {
temp.push(item);
}
temp.push(array[i]);
}
return temp 
 }

this will return new array after adding at your define location

Amit Rai
  • 289
  • 1
  • 4
  • 22
  • just want to push a object on zero length of array using this new spared operator because i'm using latest primeng datatable and this is only support spared operator push in array. like this.tradingPartners = [...this.tradingPartners, this.tradingPartner]; – ER.SHASHI TIWARI Sep 29 '17 at 12:15
  • 1
    this.array = pushdata(index,array,item) { let temp = []; for(let i = 0; i< array.length ; i ++) { if(i === index) { temp.push(item); } temp.push(array[i]); } return temp } – Amit Rai Sep 29 '17 at 12:22
1
this.tradingPartner = new TradingPartnerModel();
this.tradingPartners = [...this.tradingPartners];
this.tradingPartners.unshift(this.tradingPartner);
bluehipy
  • 2,254
  • 1
  • 13
  • 19