- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Given an array of integers return positives, whose equivalent negatives present in it in JavaScript
We are required to write a JavaScript function that takes in an array of Numbers (both positive and negative).
The function should return an array of all those positive numbers from the array whose negative equivalents are present in the array.
For example: If the input array is −
const arr = [1, 5, −3, −5, 3, 2];
Then the output should be −
const output = [5, 3];
Example
The code for this will be −
const arr = [1, 5, −3, −5, 3, 2]; const findNumbers = (arr = []) => { const count = Object.create(null); const result = []; arr.forEach(el => { if (count[−el]) { result.push(Math.abs(el)); count[−el]−−; return; }; count[el] = (count[el] || 0) + 1; }); return result; } console.log(findNumbers(arr));
Output
And the output in the console will be −
[5, 3]
- Related Articles
- Sum of all positives present in an array in JavaScript
- Pushing positives and negatives to separate arrays in JavaScript
- Removing Negatives from Array in JavaScript
- Returning the value of (count of positive / sum of negatives) for an array in JavaScript
- How to return an array whose elements are the enumerable property values of an object in JavaScript?
- How to create an array of integers in JavaScript?
- Inverting signs of integers in an array using JavaScript
- Given an array of integers, find the pair of adjacent elements that has the largest product and return that product JavaScript
- JavaScript Algorithm - Removing Negatives from the Array
- How to sort an array of integers correctly in JavaScript?
- Count groups of negatives numbers in JavaScript
- First string from the given array whose reverse is also present in the same array in C++
- Return indexes of greatest values in an array in JavaScript
- Take an array of integers and create an array of all the possible permutations in JavaScript
- How to sort an array of integers correctly JavaScript?

Advertisements