Skip to content

Commit

Permalink
Merge pull request mootools#1064 from tmallen/master
Browse files Browse the repository at this point in the history
Array.pluck
  • Loading branch information
cpojer committed Nov 4, 2011
2 parents 70be7c1 + 6d78fa9 commit df02433
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
26 changes: 26 additions & 0 deletions Docs/Types/Array.Extras.md
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions Source/Types/Array.Extras.js
Expand Up @@ -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];
});
}

});
Expand Down
12 changes: 12 additions & 0 deletions Tests/Specs/1.3/Types/Array.Extras.js
Expand Up @@ -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.