0

I need something like this:

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

But this is not working in javascript.

Is there a way to achive this mechanism in javascript?

Tolgay Toklar
  • 3,732
  • 8
  • 38
  • 63

2 Answers2

6

First, initialize fruits itself as an array

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

console.log(fruits);
AmmarCSE
  • 29,061
  • 5
  • 39
  • 52
1

You can do the following:

var fruits = []; //declared a blank array

fruits.push("Banana"); //adding 1st item
fruits.push("Orange"); //adding 2nd item
fruits.push("Apple");  //adding 3rd item
fruits.push("Mango");  //adding 4th item

//if you want to update any item then simply do the following
fruits[2] = "Lemon"
Chetan Purohit
  • 355
  • 1
  • 3
  • 16