- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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]
Advertisements