Yes, Array.map () or $ .map () does the same.
//array.map: var ids = this.fruits.map(function(v){ return v.Id; }); //jQuery.map: var ids2 = $.map(this.fruits, function (v){ return v.Id; }); console.log(ids, ids2);
http://jsfiddle.net/NsCXJ/1/
Since array.map is not supported in older browsers, I suggest sticking with the jQuery method.
If for some reason you prefer another, you can always add a polyfill to support the old browser.
You can always add your own methods to the prototype array:
Array.prototype.select = function(expr){ var arr = this;
An extended version that uses a function constructor if you pass a string. Perhaps you can play with this:
Array.prototype.select = function(expr){ var arr = this; switch(typeof expr){ case 'function': return $.map(arr, expr); break; case 'string': try{ var func = new Function(expr.split('.')[0], 'return ' + expr + ';'); return $.map(arr, func); }catch(e){ return null; } break; default: throw new ReferenceError('expr not defined or not supported'); break; } }; console.log(fruits.select('x.Id'));
http://jsfiddle.net/aL85j/
Update:
Since this has become such a popular answer, I add a similar firstOrDefault() where() + firstOrDefault() . They can also be used with the string-based function constructor approach (which is the fastest), but there is another approach here that uses the object literal as a filter:
Array.prototype.where = function (filter) { var collection = this; switch(typeof filter) { case 'function': return $.grep(collection, filter); case 'object': for(var property in filter) { if(!filter.hasOwnProperty(property)) continue;
Using:
var persons = [{ name: 'foo', age: 1 }, { name: 'bar', age: 2 }]; // returns an array with one element: var result1 = persons.where({ age: 1, name: 'foo' }); // returns the first matching item in the array, or null if no match var result2 = persons.firstOrDefault({ age: 1, name: 'foo' });
Here is a jsperf test to compare the constructor of a function and the speed of an object literal. If you decide to use the first, keep in mind that the lines must be specified correctly.
Personally, I prefer to use solutions based on object literals when filtering 1-2 properties and pass a callback function for more complex filtering.
I will end this with two general tips when adding methods to my own object prototypes:
Check for existing methods before overwriting, for example:
if(!Array.prototype.where) { Array.prototype.where =...
If you do not need to support IE8 and lower, define methods using Object.defineProperty to make them non-enumerable. If someone used for..in in an array (which is primarily wrong), it will also perform iterable properties. Just one on one.