88

How do I iterate through an existing array and add the items to a new array.

var array = [];
forEach( calendars, function (item, index) {
    array[] = item.id
}, done );

function done(){
   console.log(array);
}

The above code would normally work in JS, not sure about the alternative in node js. I tried .push and .splice but neither worked.

DACrosby
  • 11,116
  • 3
  • 39
  • 51
Ben Scarberry
  • 943
  • 2
  • 8
  • 11
  • 5
    There are a lot of wrong things with your code; that implies you haven't tried very hard to get it working! For instance, what is happening with `array[] = item.id`? That would produce a syntax error in normal js. – starwed Sep 30 '13 at 00:08

4 Answers4

168

Check out Javascript's Array API for details on the exact syntax for Array methods. Modifying your code to use the correct syntax would be:

var array = [];
calendars.forEach(function(item) {
    array.push(item.id);
});

console.log(array);

You can also use the map() method to generate an Array filled with the results of calling the specified function on each element. Something like:

var array = calendars.map(function(item) {
    return item.id;
});

console.log(array);

And, since ECMAScript 2015 has been released, you may start seeing examples using let or const instead of var and the => syntax for creating functions. The following is equivalent to the previous example (except it may not be supported in older node versions):

let array = calendars.map(item => item.id);
console.log(array);
nkron
  • 19,086
  • 3
  • 39
  • 27
10

Here is example which can give you some hints to iterate through existing array and add items to new array. I use UnderscoreJS Module to use as my utility file.

You can download from (https://npmjs.org/package/underscore)

$ npm install underscore

Here is small snippet to demonstrate how you can do it.

var _ = require("underscore");
var calendars = [1, "String", {}, 1.1, true],
    newArray = [];

_.each(calendars, function (item, index) {
    newArray.push(item);
});

console.log(newArray);
Gaurang Jadia
  • 1,516
  • 15
  • 18
9
var array = [];

//length array now = 0
array[array.length] = 'hello';
//length array now = 1
//            0
//array = ['hello'];//length = 1
Draken
  • 3,134
  • 13
  • 34
  • 54
user6335419
  • 91
  • 2
  • 2
0

var array = calendars.map(function(item) {
    return item.id;
});

console.log(array);