Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I keep getting an array inside an array when using push()?

I am trying to understand MDN's documentation on .push() and .apply() because I'm having an issue where I am ending up with an array inside an array in a project. I have set up some experimental code to illustrate my problem.

Can anyone explain why the array contents inside foo() print within another array? I am not understanding why it isn't printing one array for both console.log()instances.

var animals = [];
var chickens = 'chickens';
var cows = 'cows';

animals.push(cows);
animals.push(chickens);

console.log(animals); // > Array ["cows", "chickens"]

function foo(...animals) {
  console.log(animals); // > Array [["cows", "chickens"]] <-- why is this one inside another array?
}; 

I thought using .apply() would solve the problem but it I couldn't get it to work. For example...

animals.push.apply(animals, cows);
animals.push.apply(animals, chickens);

// Error: second argument to Function.prototype.apply must be an array
like image 600
dumdum3000 Avatar asked Mar 04 '23 03:03

dumdum3000


2 Answers

Because ... (rest/spread syntax) makes a new array out of the passed arguments - so making an array out of ["chickens", "cows"] will result in [["chickens", "cows"]]. Solve this by removing the ... in foo.

var animals = [];
var chickens = 'chickens';
var cows = 'cows';

animals.push(cows);
animals.push(chickens);

console.log(animals); 

function foo(animals) {
  console.log(animals); 
}; 

foo(animals);
.as-console-wrapper { max-height: 100% !important; top: auto; }
like image 163
Jack Bashford Avatar answered Apr 07 '23 13:04

Jack Bashford


Read about this -> Rest parameters

// "Rest parameters" receives the arguments which is 
// a like array object, and uses its indexes for creating an array.
function fn(...params) {
  console.log(params);
} 

fn("Ele", "From", "Stack"); // Multiple params will be spread as indexes of the array.
fn(["Ele", "From", "Stack"]); // In this case, one param (an array) will be used as the only index in the array.
fn(); // In this case, an empty array will be generated.
.as-console-wrapper { max-height: 100% !important; top: 0; }

On the other hand, the function apply, the second param should be an array which depicts the arguments

Array.push.apply(animals, [cows, chickens]);
like image 38
Ele Avatar answered Apr 07 '23 12:04

Ele