i have this array:
const myArray = [["Cow", 3], ["Pig", 5], ["Pig", 10], ["Pig", 4], ["Chicken", 1], ["Cow", 1], ["Cow" , 12], ["Cow", 11], ["Chicken", 12]]
and want to turn into this: (only the highest of each one)
[ [ 'Pig', 10 ], [ 'Cow', 12 ], [ 'Chicken', 12 ] ]
but with my code i cant get the last one, i cant find why tho
const myArray = [["Cow", 3], ["Pig", 5], ["Pig", 10], ["Pig", 4], ["Chicken", 1], ["Cow", 1], ["Cow" , 12], ["Cow", 11], ["Chicken", 12]]
function getHighest() {
var onlyHighest = [];
myArray.sort(
function(a,b) {
if (a[0] == b[0])
return a[1] < b[1] ? -1 : 1;
return a[0] < b[0] ? 1 : -1;
}
);
myArray.forEach((a, i) => {
var i = i+1;
if (i < myArray.length) {
if (a[0] != myArray[i][0]){
onlyHighest.push([a[0], a[1]]);
}
}
});
return console.log(onlyHighest)
// [ [ 'Pig', 10 ], [ 'Cow', 12 ] ]
}
>Solution :
Use an object to hold the current highest value for each animal. Loop through the array, replacing the value when it’s higher than the value in the object.
const myArray = [["Cow", 3], ["Pig", 5], ["Pig", 10], ["Pig", 4], ["Chicken", 1], ["Cow", 1], ["Cow" , 12], ["Cow", 11], ["Chicken", 12]]
function getHighest(array) {
let obj = {};
array.forEach(([key, value]) => {
if (key in obj) {
if (value > obj[key]) {
obj[key] = value;
}
} else {
obj[key] = value;
}
});
return Object.entries(obj);
}
console.log(getHighest(myArray));