Skip to content

Instantly share code, notes, and snippets.

@carlhannes
Last active September 25, 2022 08:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlhannes/3a375f70b27d71165a0d9fe1981df171 to your computer and use it in GitHub Desktop.
Save carlhannes/3a375f70b27d71165a0d9fe1981df171 to your computer and use it in GitHub Desktop.
groupby.js
const groupBy = (array, fn, last = false) => {
const grouped = [];
for (let index = 0; index < array.length; index += 1) {
const element = array[index];
const key = fn(element);
const foundIndex = grouped.findIndex((v) => v.key === key);
if (foundIndex === -1) {
grouped.push({ key, value: element });
} else if (last) {
grouped[foundIndex].value = element;
}
}
return grouped.map((v) => v.value);
};
/*
const groupedData = groupBy(inputData, (v) => format(new Date(v.date), 'yyyy-MM'));
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment