Last active
September 25, 2022 08:06
-
-
Save carlhannes/3a375f70b27d71165a0d9fe1981df171 to your computer and use it in GitHub Desktop.
groupby.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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