Skip to content

Instantly share code, notes, and snippets.

@iagocavalcante
Created August 14, 2020 18:41
Show Gist options
  • Save iagocavalcante/efbd34a2b87d33669b0da4054e8fd0fd to your computer and use it in GitHub Desktop.
Save iagocavalcante/efbd34a2b87d33669b0da4054e8fd0fd to your computer and use it in GitHub Desktop.
Script to groupBy and Sort
const params = [
{
name: 'p1',
timestamp: 12
},
{
name: 'p1',
timestamp: 13
},
{
name: 'p2',
timestamp: 12
},
{
name: 'p2',
timestamp: 13
}
]
const newParams = params.sort((a, b) =>
b.timestamp - a.timestamp
)
console.log(newParams[0])
function groupBy(key) {
return function group(array) {
return array.reduce((acc, obj) => {
const property = obj[key];
acc[property] = acc[property] || [];
acc[property].push(obj);
return acc;
}, {});
};
}
const groupByName = groupBy('name');
const teste = groupByName(params);
let final = []
Object.values(teste).forEach(e => {
console.log(e)
final.push(e.sort((a, b) =>
b.timestamp - a.timestamp
)[0]);
})
console.log(teste)
console.log(final)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment