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
  • 4,151
  • 8
  • 43
  • 73

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
  • 30,079
  • 5
  • 45
  • 53
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
  • 364
  • 1
  • 3
  • 16