使用JavaScript对数组中最接近的数字进行分组可以通过以下步骤完成:
function getDifference(num1, num2) {
return Math.abs(num1 - num2);
}
function groupClosestNumbers(target, array) {
let differenceMap = {};
array.forEach(num => {
const difference = getDifference(target, num);
if (!differenceMap[difference]) {
differenceMap[difference] = [];
}
differenceMap[difference].push(num);
});
const closestDifference = Math.min(...Object.keys(differenceMap));
return differenceMap[closestDifference];
}
const targetNumber = 10;
const numbersArray = [7, 12, 9, 15, 5, 8, 11];
const closestNumbers = groupClosestNumbers(targetNumber, numbersArray);
console.log(closestNumbers);
这将输出最接近目标数字10的数字集合,例如[9, 11]。
关于腾讯云的相关产品,可根据具体需求选择适合的服务,例如:
希望以上回答能帮助到您!
领取专属 10元无门槛券
手把手带您无忧上云