How to add items to array in nodejs

Javascriptnode.js

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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);

Solution 2 - Javascript

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);

Solution 3 - Javascript

var array = [];

//length array now = 0
array[array.length] = 'hello';
//length array now = 1
//            0
//array = ['hello'];//length = 1

Solution 4 - Javascript

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

console.log(array);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBen ScarberryView Question on Stackoverflow
Solution 1 - JavascriptnkronView Answer on Stackoverflow
Solution 2 - JavascriptGaurang JadiaView Answer on Stackoverflow
Solution 3 - Javascriptuser6335419View Answer on Stackoverflow
Solution 4 - JavascriptMuskan Raju SayyadView Answer on Stackoverflow