I have one array of objects:
teamScores: [
{ teamName: 'Team name 1', points: 21},
{ teamName: 'Team name 2', points: 11},
],
I need to compare the key 'points' within these two objects and return a new key saying if its the highest value. For this example the return should be:
teamScores: [
{ teamName: 'Team name 1', points: 21, isHighest: true},
{ teamName: 'Team name 2', points: 11, isHighest: false},
],
And vice versa:
teamScores: [
{ teamName: 'Team name 1', points: 11, isHighest: false},
{ teamName: 'Team name 2', points: 21, isHighest: true},
],
I tried to use .reduce() but it didn't work so well. Here is my try:
const newTeams = scoreTeams.reduce((acc, team, idx) => {
const isHigh = scoreTeams[idx].points > scoreTeams[idx - 1]?.points;
const accTeam = {
...team,
isHighest: isHigh,
};
acc[idx] = accTeam;
return acc;
}, []);
If the first object has a lower value it works well, the output:
teamScores: [
{ teamName: 'Team name 1', points: 11, isHighest: false},
{ teamName: 'Team name 2', points: 21, isHighest: true},
],
But if the first value is higher than the second, it doesn't work so well, the output:
teamScores: [
{ teamName: 'Team name 1', points: 21, isHighest: false},
{ teamName: 'Team name 2', points: 11, isHighest: false},
],
I need help to compare these objects properly, thanks in advance!
CodePudding user response:
You'd need two iterations. One to identify the highest, and one to set the property in each object.
const teamScores = [
{ teamName: 'Team name 1', points: 21},
{ teamName: 'Team name 2', points: 11},
];
const maxPoints = Math.max(...teamScores.map(({points}) => points));
const newTeams = teamScores.map(o => ({...o, isHighest: o.points === maxPoints}));
console.log(newTeams);
CodePudding user response:
map
over each object to get an array of the all the points.- Find the highest value of that array. (
Math.max
finds the highest value from a list of values. Because we're passing it an array we have tospread
the values out). - Return a new array of updated objects where
isHighest
is set totrue
orfalse
if the object'spoints
value matches thehighest
value.
const scores = [
{ teamName: 'Team name 1', points: 21 },
{ teamName: 'Team name 2', points: 11 }
];
// Collate the points
const points = scores.map(obj => obj.points);
// Find the highest point
const highest = Math.max(...points);
// `spread` out the initial object into a new object
// and add the new `isHighest` value
const out = scores.map(obj => {
return { ...obj, isHighest: obj.points === highest };
});
console.log(out);
CodePudding user response:
First find the highest with Math.max
, then compare points
of every elements with the max.
var teamScores = [
{ teamName: "Team name 1", points: 21 },
{ teamName: "Team name 2", points: 11 },
];
const max = Math.max(...teamScores.map((x) => x.points));
teamScores = teamScores.map((x) => ({...x, isHighest: x.points === max}));
console.log(teamScores);