Managing, sorting, and manipulating information with JavaScript is a ability now we have frequently delegated to 3rd birthday party libraries like lodash. Because the JavaScript language progresses, on the other hand, those options ultimately get. added to the JavaScript specification. Two such APIs for grouping of Array
information are `Array.prototype.crew
and Array.prototype.groupToMap
.
Array.prototype.crew
To crew an array of items by way of a given assets, name the crew
way with serve as that returns the grouping string:
const groups = [ { name: "Arsenal", origin: "London", tier: "legendary" }, { name: "Manchester United", origin: "Manchester", tier: "legendary" }, { name: "Liverpool", origin: "Liverpool", tier: "legendary" }, { name: "Newcastle United", origin: "Newcastle", tier: "mid" }, // Lol, awful club { name: "Tottenham", origin: "London", tier: "lol" }, ]; const tieredTeams = groups.crew(({ tier }) => tier);
The results of the array’s crew
is an object with keys that fit the grouping key:
{ mythical: [ {name: "Arsenal", origin: "London", tier: "legendary"}, {name: "Manchester United", origin: "Manchester", tier: "legendary"}, {name: "Liverpool", origin: "Liverpool", tier: "legendary"} ], mid: [ {name: "Newcastle United", origin: "Newcastle", tier: "mid"} ], lol: [ {name: "Tottenham", origin: "London", tier: "lol"} ] }
Array.prototype.groupToMap
groupToMap
returns a Map
example as a substitute of an object literal:
const tieredTeamsMap = groups.crew(({ tier }) => tier); tieredTeamsMap.has('lol') // true tieredTeamsMap.get('lol') // [{name: "Tottenham", origin: "London", tier: "lol"}]
As of the time of put up, crew
and groupToMap
are simplest to be had in Safari. Those two strategies are the most important to information control shifting ahead. Whether or not you might be manipulating information on consumer or server facet, those newly added local strategies are a lot welcomed.