0

I'm pretty new to javascript but I'm trying to push a specified number of objects to an array using the following code. When I check the console I see only one object is pushed to the array. What should I be doing differently? Thanks!

var albums = {};

function collection(numberOfAlbums) {
    array = [];
    array.push(albums);
    return array;

};

console.log(collection(12));
maxwellgover
  • 6,661
  • 9
  • 37
  • 63
  • 1
    Possible duplicate of [How to add an object into an array](http://stackoverflow.com/questions/6254050/how-to-add-an-object-into-an-array) – Gandalf the White Feb 19 '16 at 16:47
  • staxwell: Have you learned about `for` loops yet? If not, then the only thing you're probably needing is to read a beginner's tutorial. –  Feb 19 '16 at 16:48
  • Use `for-loop` to add `n` number of items..`var albums = {}; function collection(numberOfAlbums) { var array = []; for (var i = 0; i < numberOfAlbums; i++) { array.push(albums); } return array; }; console.log(collection(12));` – Rayon Feb 19 '16 at 16:51
  • You can use concat() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat – Nestor Mata Cuthbert Sep 17 '16 at 00:30

2 Answers2

1

From your code:

array.push(albums);

would add the same object each time (assuming you had added a loop) which isn't what you want.

This will add a new empty object for each iteration of numberOfAlbums:

function collection(numberOfAlbums) {
  for (var array = [], i = 0; i < numberOfAlbums; i++) {
    array.push({});
  }
  return array;
};

Here's another way using map. Array.apply trick from here.

function collection(numberOfAlbums) {
  var arr = Array.apply(null, Array(numberOfAlbums));
  return arr.map(function (el) { return {}; });
};
Andy
  • 61,948
  • 13
  • 68
  • 95
-2

I could give you the code but that is not learning. So here are the steps:

  1. use numberOfAlbums as an argument in a function.
  2. create an empty array.
  3. use numberOfAlbums in for-loops in that for-loops push albums. ==array.push(albums)== do not use {}curly brackets around albums.
  4. return the array.
jaga
  • 1
  • 1