-2
var fruits = ["Banana", "Orange", "Apple", "Mango"];

In the above array i can do fruits.push('Grapes') to insert item but what should i do for the below array to push vegetable inside vegetable array.

var fruits = ["Banana", "Orange", "Apple", "Mango", ["potato", "Tomato"]];
Coder
  • 1,917
  • 3
  • 17
  • 33
srs
  • 35
  • 1
  • 5
  • `fruits[4].push('Carrot')` – Jaromanda X May 24 '17 at 06:50
  • the question is, it the vegetables always at the end of the array, or can it be anywhere? – Nina Scholz May 24 '17 at 06:51
  • it can be anywhere – srs May 24 '17 at 06:53
  • @JaromandaX And the value of `fruits[4]` after the first assignment in the question is...? – Michael Geary May 24 '17 at 06:54
  • @MichaelGeary no, they're right the question is just worded horribly (in the way the first assignment is pointless). All they want it to push to an array in an array. – George May 24 '17 at 06:56
  • 1
    @George Oh, you are right! I couldn't figure out what the actual question was... – Michael Geary May 24 '17 at 06:57
  • 1
    @srs You've gotten a few answers and comments suggesting `fruit[4].push(...)`. But what happens when you have only two fruits in the array? Or five fruits? One answer suggests searching the original array to find the first element that is also an array, and pushing into that. But none of these really make any sense, because the problem is not clear. *Why* do you have an array with four fruits and a fifth element that is an array of vegetables? What purpose does that data structure serve? What is the actual problem you are trying to solve? – Michael Geary May 24 '17 at 07:05
  • I agree with @MichaelGeary, it's a very odd data structure. What's wrong with having two separate arrays or having an object that contains both arrays separately? – George May 24 '17 at 07:39

4 Answers4

4

You could search for the array and push the vegetable.

var vegetable = 'broccoli',
    fruits = ["Banana", "Orange", "Apple", "Mango", ["potato", "Tomato"]];

fruits.find(a => Array.isArray(a)).push(vegetable);

console.log(fruits);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can do this the following way

fruits[4].push('grapes')

Please consider ensuring the 5th element is actually an array, one of the answers here above outline how thats done.

realappie
  • 4,656
  • 2
  • 29
  • 38
  • @micheal geary I know, ensuring the element is an array would be a nice addition. But thats not what OP asked for, trying to keep it simple and to the point here. – realappie May 24 '17 at 06:56
  • Actually I was a bit confused by the question, disregard what I said! :-) – Michael Geary May 24 '17 at 07:00
0
fruits[4].push('Grapes');

Check this answer, it will be helpful. array.push() for multidimensional arrays

Red Bottle
  • 2,839
  • 4
  • 22
  • 59
0

You can do it as :

var fruits = ["Banana", "Orange", "Apple", "Mango", ["potato", "Tomato"]];
fruits[4].push('newVegetable');
dattebayo
  • 1,362
  • 9
  • 4