# Adjacent elements of array whose sum is closest to 0 - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of numbers and returns a subarray of two elements from the original array whose sum is closest to 0.

If the length of the array is less than 2, we should return the whole array.

For example: If the input array is −

const arr = [4, 4, 12, 3, 3, 1, 5, -4, 2, 2];

Here, the sum of pair [5, -4] is 1 which is closest 0 for any two adjacent elements of the array, so we should return [5, -4]

## Example

Following is the code −

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));

## Output

Following is the output in the console −

[5, -4]