Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Array.pluck #1064

Merged
merged 1 commit into from

2 participants

@ghost

Good complement to Array.invoke, this method is in Prototype and ExtJS (off the top of my head; there could be others).

Thomas Allen Array.pluck
6d78fa9
@cpojer
Owner

Sure whynot.

@cpojer cpojer merged commit df02433 into from
@arian
Owner

Very nice!

Alternative implementation without relying on .map and function calls, which should be a bit faster:


Array.implement({

    pluck: function(property){
        var length = this.length >>> 0, results = new Array(length);
        for (var i = 0; i < length; i++){
            if (i in this) results[i] = this[i][property];
        }
        return results;
    }

});

jsperf: http://jsperf.com/pluck

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Nov 4, 2011
  1. Array.pluck

    Thomas Allen authored
This page is out of date. Refresh to see the latest.
View
26 Docs/Types/Array.Extras.md
@@ -187,6 +187,32 @@ Apply a function simultaneously against two values of the array (from right-to-l
### See also:
- [MDC Array.reduceRight][]
+Array Method: pluck {#Array.pluck}
+----------------------------------
+
+Returns an array with the named property from each of the array's elements.
+
+### Syntax
+
+ var arr = myArray.pluck(prop)
+
+### Arguments
+1. prop - The named property to access on each element.
+
+### Returns
+
+* (*array*) A new array containing the property value for each element.
+
+### Example
+
+ var foo = [{ a: 1 }, { a: 2 }];
+ var bar = foo.pluck('a'); // bar is [1, 2]
+ var foo2 = [{ a: 1 }, { b: 2 }];
+ var bar2 foo2.pluck('a'); // bar2 is [1, undefined]
+
+### Notes
+
+ Undefined properties are not filtered from the returned array, as shown in the second example.
[Array]: /core/Types/Array
[MDC Array.reduce]: https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/Array/Reduce
View
6 Source/Types/Array.Extras.js
@@ -72,6 +72,12 @@ Array.implement({
if (i in this) value = value === nil ? this[i] : fn.call(null, value, this[i], i, this);
}
return value;
+ },
+
+ pluck: function(prop){
+ return this.map(function(item){
+ return item[prop];
+ });
}
});
View
12 Tests/Specs/1.3/Types/Array.Extras.js
@@ -117,3 +117,15 @@ describe('Array.reduceRight', function(){
});
+describe('Array.pluck', function(){
+
+ it('should return the specified property from each element', function(){
+ expect([{ a: 1 }, { a: 2 }].pluck('a')).toEqual([1, 2]);
+ });
+
+ it('should return undefined properties', function(){
+ expect([{ a: 1 }, { b: 2 }].pluck('a')).toEqual([1, undefined]);
+ });
+
+});
+
Something went wrong with that request. Please try again.