1

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!

asked Aug 12, 2016 at 8:47
1
  • 2
    fruits.unshift("Lemon") or fruits = ["Lemon", ...fruits] Commented Aug 12, 2016 at 8:48

5 Answers 5

2

try this:

fruits.unshift("Lemon");
answered Aug 12, 2016 at 8:48
Sign up to request clarification or add additional context in comments.

Comments

2

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 ]
answered Aug 12, 2016 at 8:56

Comments

1

Use unshift instead of push

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");
answered Aug 12, 2016 at 8:49

Comments

1

Use array splice method

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 0, "Lemon")
console.log(fruits)

JSFIDDLE

answered Aug 12, 2016 at 8:50

2 Comments

unshift is fine since he is just a beginner.
@RajaprabhuAravindasamy im just saying that it may add to his confusion. unshift was PREDEFINED to do exactly what he is needing.
0

I soted this out by using the unshift function

var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.unshift("Lemon");

hope it helps

brk
50.3k10 gold badges59 silver badges85 bronze badges
answered Aug 12, 2016 at 8:55

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.