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?
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
hope the aboave helps to understand functions to add or remove elements from arrays in javascript
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'.
You can also use concat()
in javascript to add new array element at first position and to avoid mutating array object, here is an example
const array = [2,3,4]
const addFirstElement = 1
const newArray = [addFirstElement].concat(array)
console.log(newArray); // [ 1,2,3,4]
You can also use concat() to append item at an end of an array.
const array = [1,2,3,4]
const newLastElement = 5;
const newArray = array.concat(newLastElement);
console.log(newArray); // [ 1,2,3,4,5]
Thanks.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly