- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Pair of (adjacent) elements of an array whose sum is lowest JavaScript
We are required to write a JavaScript function that takes in an array of numbers. The function should return a subarray of two adjacent elements from the original array whose sum is the least amongst all adjacent pairs of the array.
If the length of the array is less than 2, we should return boolean false.
For example, If the input array is −
const arr = [41, 44, -12, 13, -23, 1, 5, -4, 2, 2];
Here, the sum of pair [-23, 1] is -22 which is the least for any two adjacent elements of the array, so the function should return [-23, 1]
The code for this will be −
const arr = [41, 44, -12, 13, -23, 1, 5, -4, 2, 2]; const leastSum = arr => { if(arr.length <= 2){ return false; }; const creds = arr.reduce((acc, val, ind) => { let { smallest, startIndex } = acc; const next = arr[ind+1] ; if(!next){ return acc; } const sum = val + next; if(sum < smallest){ startIndex = ind; smallest = sum; }; return { startIndex, smallest }; }, { smallest: Infinity, startIndex: -1 }); const { startIndex } = creds; return [arr[startIndex], arr[startIndex + 1]]; }; console.log(leastSum(arr));
Following is the output on console −
[-23, 1]
- Related Articles
- Adjacent elements of array whose sum is closest to 0 - JavaScript
- Pair whose sum exists in the array in JavaScript
- Sum of distinct elements of an array - JavaScript
- Given an array of integers, find the pair of adjacent elements that has the largest product and return that product JavaScript
- Sum of distinct elements of an array in JavaScript
- Write:(a) a pair of integers whose sum is $-8$.(b) a pair of integers whose difference is ( -12 ).(c) a pair of integers whose sum is $0$
- How to find a group of three elements in an array whose sum equals some target sum JavaScript
- Rearrange an array to minimize sum of product of consecutive pair elements in C++
- Sum of all the non-repeating elements of an array JavaScript
- Absolute sum of array elements - JavaScript
- Write a pair of integers whose sum is 7.
- Thrice sum of elements of array - JavaScript
- Finding desired sum of elements in an array in JavaScript
- Maximum sum of difference of adjacent elements in C++
- Highest and lowest in an array JavaScript

Advertisements