How to add new array element at the start of an array in javascript?


I have already created a array dynamically using Ajax,  but now when i am getting new values to server, sometime i need to add that array on first position based on requirements, so how can i add a new element of an array to first position using javascript(preferred) or jQuery?


Asked by:- jaiprakash
0
: 2470 At:- 11/20/2017 7:11:13 AM
javascript add element to beginning of array javascript javascript array insert at index






2 Answers
profileImage Answered by:- Sam

Unshift and Shift are the functions which can be used to add or remove elements from the array starting point, while Push and pop are the functions which is used to add element or remove relement at the end of the array

so basically what you need is

var a = [12, 24, 50, 100]; //this is your array
a.unshift(11); // add element add the start of an array
console.log(a); // this will be your result [11,12, 24, 50, 100]

here is a simple diagram created by me

image-diagram-of-javascript-add-remove-element-at-start-or-end-using-shift-unshift-push-pop.png

hope the aboave helps to understand functions to add or remove elements from arrays in javascript

2
At:- 11/21/2017 1:09:51 PM
great explanation using the image, thanks 0
By : jaiprakash - at :- 11/22/2017 7:26:20 AM


profileImage Answered by:- neena

The above answer works well, but I think it is better to use Javascript .splice() method, which is used to add/remove items from an array, here is the example of it.

var arr = [12, 30, 34, 55];
arr.splice(0, 0, 11);
console.log(arr);

Output of above will give arr value as below

[
  11,
  12,
  20,
  34,
  55
]

If you want to understand array.splice method, here is it's syntax

array.splice(PositionToAddRemoveItems, HowManyItemsToRemove, Item1ToAdd, ....., ItemXtoAdd)

So basically, that's why we used arr.splice(0, 0, 11);

to add item a 0th (1st) position,

0 elements to remove

and added new item with value '11'.

1
At:- 6/13/2021 5:55:25 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly