Roufail
Roufail

Reputation: 573

how to prepend new item to array in typescript

i need to prepend value in typescript objects array

Example if array is

[
   {'title':'this is post title1','content':'this is post content1'},
   {'title':'this is post title2','content':'this is post content2'},
   {'title':'this is post title3','content':'this is post content3'},
   {'title':'this is post title4','content':'this is post content4'},
   {'title':'this is post title5','content':'this is post content5'},
]

i want when i put new item in the first of this array like prepend in jQuery

[
   {'title':'this is new item title','content':'this is new item content'},
   {'title':'this is post title1','content':'this is post content1'},
   {'title':'this is post title2','content':'this is post content2'},
   {'title':'this is post title3','content':'this is post content3'},
   {'title':'this is post title4','content':'this is post content4'},
   {'title':'this is post title5','content':'this is post content5'},
]

thanks in advance

Upvotes: 3

Views: 9597

Answers (4)

Malcor
Malcor

Reputation: 2721

You can solve it with splice.

arr.splice(index, 0, item);

From another SO question

Upvotes: 2

Jeroen van Langen
Jeroen van Langen

Reputation: 22038

It cannot be done with jquery, because it is functionality belongs to the javascript array object.

You could use the array function unshift() for that.

Upvotes: 2

Andrew Lively
Andrew Lively

Reputation: 2153

You can use unshift to prepend items to an array:

const myArray = [ 2, 3, 4 ]

myArray.unshift(1)

console.log(myArray); // [ 1, 2, 3, 4 ]

You can find the docs here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift

Upvotes: 9

CharybdeBE
CharybdeBE

Reputation: 1843

You can use the ... operator

Eg :

 let myArray = [ 1,2,3,4,5 ];
 myArray = [0, ...myArray];

Upvotes: 7

Related Questions