Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

หาค่าที่แตกต่างในสองอาร์เรย์ตัวเลขใน JavaScript

เราต้องเขียนฟังก์ชันที่รับอาร์เรย์ตัวเลขและคืนค่าองค์ประกอบจากอาร์เรย์ที่ไม่ใช่ของร่วมของทั้งสอง

ตัวอย่าง: หากสองอาร์เรย์คือ:

const arr1 = [2, 4, 2, 4, 6, 4, 3]; const arr2 = [4, 2, 5, 12, 4, 1, 3, 34];

ผลลัพธ์

ผลลัพธ์ควรเป็น:

const output = [ 6, 5, 12, 1, 34 ]

ตัวอย่าง

โค้ดสำหรับนี้:

const arr1 = [2, 4, 2, 4, 6, 4, 3]; const arr2 = [4, 2, 5, 12, 4, 1, 3, 34]; const deviations = (first, second) => { const res = []; for(let i = 0; i < first.length; i++){ if(second.indexOf(first[i]) === -1){ res.push(first[i]); } }; for(let j = 0; j < second.length; j++){ if(first.indexOf(second[j]) === -1){ res.push(second[j]); }; }; return res; }; console.log(deviations(arr1, arr2));

ผลลัพธ์

ผลลัพธ์ในคอนโซล:

[6, 5, 12, 1, 34 ]