'Another if statement before it goes to the second if statement
I have a function where 2 players with difference in weight will be joined in 1 array. As we can see on the result of the snippet,
Player 2 and Player 5 are on the same array. It happens because player 2 has 1905 weight and player 5 has 1910 weight. That means their weight difference didn't exceed diference of 15. They only have 5 weight difference.
const source = [
{ entryID: 1, entryName: 'player1', weight: 1900 },
{ entryID: 2, entryName: 'player2', weight: 1900 },
{ entryID: 3, entryName: 'player3', weight: 1905 },
{ entryID: 4, entryName: 'player4', weight: 1905 },
{ entryID: 5, entryName: 'player5', weight: 1910 },
{ entryID: 6, entryName: 'player6', weight: 1910 },
{ entryID: 7, entryName: 'player7', weight: 1920 },
{ entryID: 8, entryName: 'player8', weight: 1930 },
{ entryID: 9, entryName: 'player9', weight: 1935 },
{ entryID: 10, entryName: 'player10', weight: 1940 },
{ entryID: 11, entryName: 'player11', weight: 1955 },
{ entryID: 12, entryName: 'player12', weight: 1960 },
]
function newCombine(data, difference) {
let nonMatched = [...data]
const groups = {}
for (let i = 0; i < nonMatched.length - 1; i++) {
const first = nonMatched[i]
inner: for (let j = nonMatched.length - 1; j > i; j--) {
const second = nonMatched[j]
const delta = Math.abs(first.weight - second.weight)
//I think i need to add more if statement here before it goes to if (delta <= difference && first.entryName !== second.entryName) {
if (delta <= difference && first.entryName !== second.entryName) {
const groupKey = `${first.weight}_${second.weight}`
groups[groupKey] = [first, second]
nonMatched = nonMatched.filter(
obj => obj.entryID != first.entryID && obj.entryID != second.entryID
)
i = -1
break inner
}
}
}
return { ...groups, ...nonMatched }
}
const a = newCombine(source, 15)
console.log(a)
Now my target is, how can i prioritize the players with the same weight joined in array?
This is my target output:
{
1900_1900: [{
entryID: 1,
entryName: "player1",
weight: 1900
}, {
entryID: 2,
entryName: "player2",
weight: 1900
}],
1905_1905: [{
entryID: 3,
entryName: "player3",
weight: 1905
}, {
entryID: 4,
entryName: "player4",
weight: 1905
}],
1915_1920: [{
entryID: 5,
entryName: "player5",
weight: 1915
}, {
entryID: 6,
entryName: "player6",
weight: 1920
}],
1930_1940: [{
entryID: 7,
entryName: "player7",
weight: 1930
}, {
entryID: 8,
entryName: "player8",
weight: 1940
}]
We can see here that the players who has same weight are joined in the same array. They're being prioritized by the function followed by the players with the weight difference.
How can i achieve this target of mine? Thank you
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
