我们需要编写一个JavaScript函数,该函数接受一个Numbers数组(正数和负数)。
该函数应返回一个数组,其中包含该数组中所有负数均等于负数的正数。
例如:如果输入数组是-
const arr = [1, 5, −3, −5, 3, 2];
那么输出应该是-
const output = [5, 3];
为此的代码将是-
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));输出结果
控制台中的输出将是-
[5, 3]