

- 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
Return the greatest possible product of n numbers from the array in JavaScript
We are required to write a JavaScript function that takes in an array of Numbers as the first argument and a number, say n, as the second argument.
Our function should calculate and return the greatest possible product of n numbers from the array.
Example
The code for this will be −
const getHighestProduct = (arr, num) => { let prod = 1; const sorter = (a, b) => a - b; arr.sort(sorter); if (num > arr.length || num & 2 && arr[arr.length - 1] < 0) { return; }; if (num % 2) { prod = arr.pop(); num--; }; while (num) { prod *= arr[0] * arr[1] > arr[arr.length - 2] * arr[arr.length - 1] ? arr.shift() * arr.shift() : arr.pop() * arr.pop(); num -= 2; }; return prod; } console.log(getHighestProduct([1, 10, -5, 1, -100], 3)); console.log(getHighestProduct([3, 4, 5, 6, 7], 3)); console.log(getHighestProduct([3, 4, -5, -6, -7], 3));
Output
And the output in the console will be −
5000 210 168
- Related Questions & Answers
- Find the greatest product of three numbers in JavaScript
- Subarray with the greatest product in JavaScript
- Find the largest palindrome number made from the product of two n digit numbers in JavaScript
- Return indexes of greatest values in an array in JavaScript
- Generate n random numbers between a range and pick the greatest in JavaScript
- Find the Product of first N Prime Numbers in C++
- Take two numbers m and n & return two numbers whose sum is n and product m in JavaScript
- Get n numbers from array starting from given point JavaScript
- Product of all other numbers an array in JavaScript
- Smallest possible length constituting greatest frequency in JavaScript
- Smallest possible number divisible by all numbers from 1 to n in JavaScript
- Product of numbers present in a nested array in JavaScript
- Given an array of integers, find the pair of adjacent elements that has the largest product and return that product JavaScript
- Return the sum of two consecutive elements from the original array in JavaScript
- Length of the longest possible consecutive sequence of numbers in JavaScript
Advertisements