เราต้องเขียนฟังก์ชันที่รับอาร์เรย์ตัวเลข (บวกและลบ) คืนอาร์เรย์ของตัวเลขบวกที่มีค่าติดลบตรงข้ามอยู่ในอาร์เรย์ด้วย
ตัวอย่าง: [1, 5, -3, -5, 3, 2] → [5, 3] (เพราะมี -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]