views:

354

answers:

3

I have a javascript object array:

array = [ {x1, y1}, {x2, y2}, ... {xn, yn} ]

I want to create a new array of just the x values:

[ x1, x2, ... xn ]

I could do this easily in a for loop...:

var newarray = [];
for (var i = 0; i < array.length; i++){
     newarray.push(array[i].x);
}

...but I'm wondering if there's a nice one liner way to do this using jquery or even regular javascript?

+8  A: 

You can do this with map:

var newarray = jQuery.map(array, function (item) { return item.x; });
Gabe Moothart
A: 

Granted this is for working with a lot of data, you could use jLinq (disclaimer: my project) to select and query your records and then return what you want.

Again, this is really for when you're working with a lot of objects and making queries, but you might be able to get some ideas looking at the source code.

Hugoware
+2  A: 

ECMAScript 5 features a native map() method:

var newArray = array.map(function(value) { return value.x; });

In FF, this should even be faster than looping, but that's not true for all browsers (Opera); others don't even support it (IE).

Christoph
If he doesn't care about a cross browser solution then in FF (which supports Javascript 1.8) he could do:var arr = array.map(function(v) v.x);or: var arr = [v.x for each (v in array)];
Prestaul
Unfortunately, cross browser compatibility is necessary.
mawaldne