我有一組物件:
teamScores: [
{ teamName: 'Team name 1', points: 21},
{ teamName: 'Team name 2', points: 11},
],
我需要比較這兩個物件中的關鍵“點”并回傳一個新鍵,說明它是否為最高值。對于這個例子,回傳應該是:
teamScores: [
{ teamName: 'Team name 1', points: 21, isHighest: true},
{ teamName: 'Team name 2', points: 11, isHighest: false},
],
反之亦然:
teamScores: [
{ teamName: 'Team name 1', points: 11, isHighest: false},
{ teamName: 'Team name 2', points: 21, isHighest: true},
],
我嘗試使用 .reduce() 但效果不佳。這是我的嘗試:
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;
}, []);
如果第一個物件的值較低,則效果很好,輸出:
teamScores: [
{ teamName: 'Team name 1', points: 11, isHighest: false},
{ teamName: 'Team name 2', points: 21, isHighest: true},
],
但如果第一個值高于第二個值,則效果不佳,輸出:
teamScores: [
{ teamName: 'Team name 1', points: 21, isHighest: false},
{ teamName: 'Team name 2', points: 11, isHighest: false},
],
我需要幫助才能正確比較這些物件,在此先感謝!
uj5u.com熱心網友回復:
你需要兩次迭代。一個用于識別最高值,一個用于設定每個物件中的屬性。
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);
uj5u.com熱心網友回復:
map在每個物件上獲取所有點的陣列。- 找到該陣列的最大值。(
Math.max從值串列中找到最大值。因為我們將它傳遞給一個陣列,所以我們必須spread將值輸出)。 - 回傳一個新的更新物件陣列,其中
isHighest設定為true或false物件的points值是否與該值匹配highest。
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);
uj5u.com熱心網友回復:
首先用 找到最高的Math.max,然后將points每個元素與最大值進行比較。
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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/487484.html
標籤:javascript
