You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript算法:从数组中查找面积最接近目标的对象

JavaScript 实现查找面积最接近的对象

完整实现代码

// 已提供的面积计算工具函数
const area = (width, height) => width * height;

function getMostSimilarObject(originalObject, validObjects) {
  // 前置参数校验(可选,针对异常输入场景)
  if (!originalObject || !validObjects?.length) {
    return null;
  }
  // 预计算原始对象面积,避免重复计算
  const originalArea = area(originalObject.width, originalObject.height);

  // 遍历待匹配数组,迭代筛选面积差最小的对象
  return validObjects.reduce((mostSimilar, currentObj) => {
    const currentDiff = Math.abs(area(currentObj.width, currentObj.height) - originalArea);
    const similarDiff = Math.abs(area(mostSimilar.width, mostSimilar.height) - originalArea);
    // 保留差值更小的对象
    return currentDiff < similarDiff ? currentObj : mostSimilar;
  }, validObjects[0]);
}

调用测试示例

const originalObject = {
  width: 1090,
  height: 723,
}
const validObjects = [
  { width: 1080, height: 1080 }, 
  { width: 1080, height: 1350 },
  { width: 1080, height: 750 }
]
// 调用后返回 {width: 1080, height: 750},符合预期
console.log(getMostSimilarObject(originalObject, validObjects))

实现说明

  • 时间复杂度为O(n),仅需遍历待匹配数组1次,对于3-10个元素的场景性能完全足够
  • 预计算原始对象面积,减少不必要的重复运算
  • 用差值的绝对值判断接近程度,不管面积偏大还是偏小都可以正确匹配
  • 可选的前置参数校验可以避免空输入导致的运行报错

内容的提问来源于stack exchange,提问作者Raul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 03:36:04