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]