JSFiddle - React, Tailwind, and code Playground
by dying_sakura
JavaScript
const source = [{
entryID: 1,
entryName: 'player1',
weight: 1900,
},
{
entryID: 2,
entryName: 'player2',
weight: 1915,
},
{
entryID: 3,
entryName: 'player3',
weight: 1920,
},
{
entryID: 4,
entryName: 'player4',
weight: 1925,
},
{
entryID: 5,
entryName: 'player5',
weight: 1930,
},
{
entryID: 6,
entryName: 'player6',
weight: 1935,
},
{
entryID: 7,
entryName: 'player7',
weight: 1940,
},
{
entryID: 8,
entryName: 'player8',
weight: 1950,
},
{
entryID: 9,
entryName: 'player9',
weight: 1960,
},
{
entryID: 10,
entryName: 'player10',
weight: 1965,
},
]
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)
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 }
}
var result = newCombine(source)
console.log(result);