总和最接近0的数组的相邻元素-JavaScript
我们需要编写一个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]