Permalink
Browse files

Merge pull request #1064 from tmallen/master

Array.pluck
  • Loading branch information...
2 parents 70be7c1 + 6d78fa9 commit df024334c6e124dfd7f0b8f62511dbaa426fff05 @cpojer cpojer committed Nov 4, 2011
Showing with 44 additions and 0 deletions.
  1. +26 −0 Docs/Types/Array.Extras.md
  2. +6 −0 Source/Types/Array.Extras.js
  3. +12 −0 Tests/Specs/1.3/Types/Array.Extras.js
View
@@ -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
@@ -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];
+ });
}
});
@@ -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]);
+ });
+
+});
+

0 comments on commit df02433

Please sign in to comment.