数组中和最接近 0 的相邻元素 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/6 13:00:17
我们需要编写一个 JavaScript 函数,该函数接受一个数字数组,并从原始数组中返回两个元素的子数组,其和最接近 0。
如果数组的长度小于 2,我们应该返回整个数组。
例如:如果输入数组是 −
const arr = [4, 4, 12, 3, 3, 1, 5, -4, 2, 2];
这里,对 [5, -4] 的和为 1,对于数组的任何两个相邻元素来说,它最接近 0,所以我们应该返回 [5, -4]
示例
以下是代码 −
const arr = [4, 4, 12, 3, 3, 1, 5, -4, 2, 2];
const closestElements = (arr, sum) => {
if(arr.length <= 2){
return arr;
}
const creds = arr.reduce((acc, val, ind) => {
let { closest, startIndex } = acc;
const next = arr[ind+1];
if(!next){
return acc;
}
const diff = Math.abs(sum - (val + next));
if(diff < closest){
startIndex = ind;
closest = diff;
};
return { startIndex, closest };
}, {
closest: Infinity,
startIndex: -1
});
const { startIndex: s } = creds;
return [arr[s], arr[s+1]];
};
console.log(closestElements(arr, 1));
输出
以下是控制台中的输出 −
[5, -4]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

