|
group
Overview of group
groupgroup is an action that allows you to group an array of objects keyed on a selected property. A new object is created with each selected item as a property. Each of these properties will be set to an array that will contain a collect of the items in that group. Usageobjx([]).group( selector [, behaviour]);
SelectorsIf you use the function selector, you must specify the behaviour otherwise you will end up with a .group requires a selector error. ExampleThe following example groups people objects into two groups by whether they can vote or not. var peopleByCanVote = objx([
{ name: "Mat", age: 27 },
{ name: "Laurie", age: 25 },
{ name: "Simon", age: 12 },
{ name: "Omari", age: 13 },
{ name: "Sarah", age: 5 },
{ name: "Corey", age: 2 }
]).group(function(){ return age >= 18; }, ONew);The above code returns a new object that looks like this: {
true: [ (length=2) ],
false: [ (length=4) ]
}The following example uses a string selector to group by city. // a set of complex objects
var o = [
{ name: "Mat", address: { city: "London", postcode: { inner: "123", outer: "456" } } },
{ name: "Simon", address: { city: "London", postcode: { inner: "246", outer: "810" } } },
{ name: "Omari", address: { city: "Dudley", postcode: { inner: "987", outer: "654" } } }
];
// collect the outer postcodes
objx(o).group("address.postcode.city");
// returns objx({"London": [{ name: "Mat", address: { city: "London", postcode: { inner: "123", outer: "456" } } }, { name: "Simon", address: { city: "London", postcode: { inner: "246", outer: "810" } } }], "Dudley": [{ name: "Omari", address: { city: "Dudley", postcode: { inner: "987", outer: "654" } } }]})
| ||||
► Sign in to add a comment