Skip to content

Instantly share code, notes, and snippets.

@superelement
superelement / groupByKeepOrder
Last active March 1, 2023 07:10
Alternative to LoDash 'groupBy' that preserves original order
/**
* @description Groups items from an array into an array of objects, grouped by a property 'prop' name, maintaining original order. Based on functionality of LoDash's 'groupBy' function, but, unlike LoDash, preserves original array's order and returns an array instead of an object.
* @param arr {array of objects} - Objects within array should contain a property marked by the 'prop' argument, or else they will be excluded from the output and a warning will be logged.
* @param prop {string} Propery to use for grouping. The value of this will be converted to a string when creating group names.
*/
var groupByKeepOrder = function(arr, prop) {
var newArr = [] // array to return, keeps track of order
, wrapObj = {}; // temporary object used for grouping
_.forEach(arr, function (item) {