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
: 575 At:- 11/20/2017 7:11:13 AM
javascript add element to beginning of array javascript javascript array insert at index






1 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

1
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





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