im having a difficulties on leaning javascript, what i want to achieve is to add an item on the top of the list instead on the Last index.
below is my code:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon");
i need to insert the Lemon before Banana..
thanks!
5 Answers 5
try this:
fruits.unshift("Lemon");
Comments
You can use unshift(), as told before, but I would recommend learning splice().
Basically splice() can be used for adding and removing elements from an array:
Removing:
var myArray = [1, 2, 3, 4, 5];
var newArr = myArray.splice(1, 2); // starting from index 1 take two elements from `myArray` and put them into `newArr`
Results:
myArray:[ 1, 4, 5 ],newArr:[ 2, 3 ]
Adding:
var myArray = [1, 2, 3, 4, 5];
myArray.splice(1, 0, "test"); // starting from index 1 take zero elements and add "test" to `myArray`
Result:
myArray:[ 1, "test", 2, 3, 4, 5 ]
Comments
Use unshift instead of push
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");
Comments
Use array splice method
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 0, "Lemon")
console.log(fruits)
I soted this out by using the unshift function
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");
hope it helps
fruits.unshift("Lemon")orfruits = ["Lemon", ...fruits]