
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Finding a pair that is divisible by some number in JavaScript
We are required to write a JavaScript function that takes in an array of Numbers as the first argument, let's call it arr and a single number as the second argument, let's call it num.
The function should find all such pairs from the array where −
arr[i] + arr[j] = num, and i < j
For example −
If the input array and the number is −
const arr = [1, 2, 3, 4, 5, 6]; const num = 4;
Then the output should be −
const output = [ [1, 3], [2, 6], [3, 5] ];
Example
The code for this will be −
const arr = [1, 2, 3, 4, 5, 6]; const num = 4; const divisibleSumPairs = (arr = [], num) => { const res = []; const { length } = arr; for(let i = 0; i < length; i++){ for(let j = i + 1; j < length; j++){ const sum = arr[i] + arr[j]; if(sum % num === 0){ res.push([arr[i], arr[j]]); } } } return res; }; console.log(divisibleSumPairs(arr, num));
Output
And the output in the console will be −
[ [ 1, 3 ], [ 2, 6 ], [ 3, 5 ] ]
- Related Questions & Answers
- Generating a random number that is divisible by n in JavaScript
- Finding smallest number that satisfies some conditions in JavaScript
- Smallest number that is divisible by first n numbers in JavaScript
- Finding the count of numbers divisible by a number within a range using JavaScript
- Finding closest pair sum of numbers to a given number in JavaScript
- Greatest number divisible by n within a bound in JavaScript
- Finding whether a number is triangular number in JavaScript
- Finding number that appears for odd times - JavaScript
- Find if a number is divisible by every number in a list in C++
- Sum which is divisible by n in JavaScript
- Check if a large number is divisible by 20 in C++
- Number is divisible by 29 or not in C++
- Is the digit divisible by the previous digit of the number in JavaScript
- Finding matching pair from an array in JavaScript
- Minimum value that divides one number and divisible by other in C++
Advertisements