I'm using the matomo reports api to pull out some data in js. For some charts, I'm in the need to sort the array data based on inner property value ("val"), further to get only the 3 highest (Hong Kooong, Munich, Tokyo). Finally, this data should be used for the creation of a new key/val object (newObj).
This is what my code looks like what does what it should. I would be interested if it can be optimized using es6 syntax.
let data = {
0 : {"label":"New York", "val": 20},
1 : {"label":"Rio", "val": 10},
3 : {"label":"Tokyo", "val": 50},
4 : {"label":"Santiago", "val": 20},
5 : {"label":"Hong Kooong", "val": 100},
6 : {"label":"Munich", "val": 90},
}
let compare = (a, b) => {
let valA = a.val;
let valB = b.val;
let c = 0;
if (valA > valB) {
c = 1;
} else if (valA < valB) {
c = -1;
}
return c * -1;
}
let dataArray = Object.values(data).sort(compare)
dataArray = dataArray.slice(0, 3)
let newLabel = []
let newValue = []
Object.keys(dataArray).map(function(key, index) {
newLabel.push(dataArray[index]['label'])
newValue.push(dataArray[index]['val'])
});
let newObj = {}
newObj.data = {}
newObj.data.labels = newLabel
newObj.data.values = newValue
console.log(newObj)