Skip to content

Instantly share code, notes, and snippets.

@superelement
Last active March 1, 2023 07:10
Show Gist options
  • Save superelement/69677823acf20d45fdbb11a051486936 to your computer and use it in GitHub Desktop.
Save superelement/69677823acf20d45fdbb11a051486936 to your computer and use it in GitHub Desktop.
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) {
// gets property name to group by and converts it to a string for grouping purposes
var propName = item[prop];
if(propName) {
propName = propName.toString();
// checks if group exists already and creates a new group if not, pushing it into the array to return ('newArr')
if (!wrapObj[propName]) {
wrapObj[propName] = [];
newArr.push(wrapObj[propName]);
}
// adds item to the group
wrapObj[propName].push(item);
} else {
console.warn("utils -> groupByKeepOrder", "Property '" + prop + "' not found within object. It will be ignored from the output.", item);
}
});
delete wrapObj; // don't need this anymore
return newArr
}
@akhayoon
Copy link

works great man, thanks

@nandakumardevadas
Copy link

Working as expected. Thanks for the Gist.

@karthicktam
Copy link

Thanks for the code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment