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!

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");
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 ]

Comments

1

Use unshift instead of push

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

Comments

1

Use array splice method

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

JSFIDDLE

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.