

- 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
Positive, negative and zeroes contribution of an array in JavaScript
Suppose we have an array of integers, (positive, negative and zero) like this −
const arr = [23, -1, 0, 11, 18];
We are required to write a JavaScript function that takes in one such array as the first and the only argument. The function should then find the fractional ratio for all three different groups, namely positive, negative and zero.
For example −
For the above array, its length is 5, the output for this array should be −
const output = [.2, .2, .6];
The output array will always contain 3 numbers, representing the fractional ratio of negative, zero and positive integers respectively. One rough way to verify our answer is to add these three values and check if they near 1 or not, if they do, we are very likely to have solved the problem correctly.
Example
The code for this will be −
const arr = [23, -1, 0, 11, 18]; const findRatio = (arr = []) => { const { length } = arr; const res = [0, 0, 0]; for(let i = 0; i < arr.length; i++){ const el = arr[i]; const key = el / Math.abs(el || 1); res[key + 1]++; }; return res.map(el => el / length); }; console.log(findRatio(arr));
Output
And the output in the console will be −
[0.2, 0.2, 0.6]
- Related Questions & Answers
- Split an array of numbers and push positive numbers to JavaScript array and negative numbers to another?
- Sum a negative number (negative and positive digits) - JavaScript
- Reversing negative and positive numbers in JavaScript
- Find the Pairs of Positive Negative values in an Array using C++
- Java Program to convert positive int to negative and negative to positive
- How to print positive and negative infinity values in JavaScript?
- Counting number of positive and negative votes in MySQL?
- Implement Bubble sort with negative and positive numbers – JavaScript?
- Positive Testing and Negative Testing with Examples
- Test array values for positive or negative infinity in Numpy
- Finding array number that have no matching positive or negative number in the array using JavaScript
- What are the positive and negative impacts of a working mother?
- Print all the pairs that contains the positive and negative values of an element in C++
- How to find the groupwise number of positive and negative values in an R data frame?
- Lambda expression in Python to rearrange positive and negative numbers