Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the jetpack domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /home/feedavenue.com/public_html/wp-includes/functions.php on line 6114
JavaScript Array Group - Feedavenue
Wednesday, December 25, 2024
HomeTechnologySoftwareJavaScript Array Group

JavaScript Array Group

Date:

Related stories

spot_imgspot_img

Managing, sorting, and manipulating data with JavaScript is a skill we’ve often delegated to third party libraries like lodash. As the JavaScript language progresses, however, these features eventually get. added to the JavaScript specification. Two such APIs for grouping of Array data are `Array.prototype.group and Array.prototype.groupToMap.

Array.prototype.group

To group an array of objects by a given property, call the group method with function that returns the grouping string:

const teams = [
   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 = teams.group(( tier ) => tier);

The result of the array’s group is an object with keys that match the grouping key:


  legendary: [
    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 instance instead of an object literal:

const tieredTeamsMap = teams.group(( tier ) => tier);

tieredTeamsMap.has('lol') // true

tieredTeamsMap.get('lol') // [name: "Tottenham", origin: "London", tier: "lol"]

As of the time of publish, group and groupToMap are only available in Safari. These two methods are crucial to data management moving forward. Whether you’re manipulating data on client or server side, these newly added native methods are much welcomed.



Source link

Latest stories

spot_img