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
How to get the numbers which can divide all values in an array - JavaScript
We are required to write a JavaScript function that takes in an array of numbers and returns a number which can exactly divide all the numbers in the array.
Let’s say the following is our array −
const arr = [4, 6, 34, 76, 78, 44, 34, 26, 88, 76, 42];
Example
Following is the code −
const arr = [4, 6, 34, 76, 78, 44, 34, 26, 88, 76, 42];
const dividesAll = el => {
const result = [];
let num;
for (num = Math.floor(el / 2); num > 1; num--){
if (el % num === 0) {
result.push(num);
}
};
return result;
};
const dividesArray = arr => {
return arr.map(dividesAll).reduce((acc, val) => {
return acc.filter(el => val.includes(el));
});
};
console.log(dividesArray(arr));
Output
This will produce the following output in console −
[ 2 ]
Advertisements