简体   繁体   中英

create an array from an existing array

I want to create an array by extracting the dates of some other array and then comma separate the values into a string.

      array.push({date:created_at,username:user});
      for (i in array) {
      var combined=new array();
      combined = array[i].date;
                }   
      console.log(combined);

I am new to javascript and hard to follow in arrays.Thanks !! Can anyone also recommend me a good book for javascript?

Try this

var originalArray = [{date:"2012-01-01", username: "first"}, {date:"2012-01-02", username: "second"}];

// First step: Get a dateArray with only the dates
var dateArray = [];
for (var i in originalArray) {
    dateArray.push(originalArray[i].date);
}   

// Or if you prefer to cut a few lines
// dateArray = originalArray.map(function(x) { return x.date; } );

// Second step: Get it as a comma separated string
var datesString = dateArray.join(",");

console.log(dateArray); // ["2012-01-01","2012-01-02"]
console.log(datesString); // 2012-01-01,2012-01-02

One of the more popular books is "Javascript The Good Parts" by Douglas Crockford http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742

I personally am partial to Javascript the Good parts, but there is a whole community wiki on books for programming. As for your question if you want to use a string, you need to use a string not an array for the combined variable.

array.push({date:created_at,username:user});
var combined = array.map(function(a) { return a.date; }).join(", ");

There are certainly better ways of doing it, but this is just a quick example of something which would work. By concatenating with a string, it implicitly casts the array[i].date into a string if it wasn't already.

Edit: Fixed my code to not be so awful.

here is the code :

var firstArray = new Array(new Date(), "hello", "something", new Date());
var combined = new Array();

for(i in firstArray) {
   if(firstArray[i] instanceof Date) {
      combined[combined.length] = firstArray[i];
   }
 }

 var theString = combined.join(",");

 alert(combined.length);
 alert(theString);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM