Created
August 14, 2020 18:41
-
-
Save iagocavalcante/efbd34a2b87d33669b0da4054e8fd0fd to your computer and use it in GitHub Desktop.
Script to groupBy and Sort
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 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