Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Nice way to create an array from an object array

I have a javascript object array:

array = [ {x:'x1', y:'y1'}, {x:'x2', y:'y2'}, ... {x:'xn', y:'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?

like image 879
mawaldne Avatar asked Jun 11 '09 19:06

mawaldne


1 Answers

You can do this with map:

var newarray = jQuery.map(array, function (item) { return item.x; });
like image 100
Gabe Moothart Avatar answered Nov 15 '22 10:11

Gabe Moothart