
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Two Closest Elements to a Specific Number in an Array using JavaScript
Problem
We are required to write a JavaScript function that takes in an array of sorted integers, arr, as the first argument and a target number, as the second argument.
Our function should return an array of exactly two numbers that exists in the array arr and are closest to target. The output array should also be sorted in increasing order.
For example, if the input to the function is
Input
const arr = [1, 2, 3, 4, 5]; const target = 3;
Output
const output = [2, 3];
Example
Following is the code −
const arr = [1, 2, 3, 4, 5]; const target = 3; const findClosest = (arr = [], target = 1) => { const size = 2; return arr.sort((a, b) => { const distanceA = Math.abs(a - target) const distanceB = Math.abs(b - target) if (distanceA === distanceB) { return a - b } return distanceA - distanceB }).slice(0, size) .sort((a, b) => a - b); }; console.log(findClosest(arr, target));
Output
[2, 3]
Advertisements