เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับ Numbers สองอาร์เรย์ พูดก่อนและที่สอง และตรวจสอบความเท่าเทียมกัน
ความเท่าเทียมกันในกรณีของเราจะถูกกำหนดโดยหนึ่งในสองเงื่อนไขนี้ -
-
อาร์เรย์จะเท่ากันหากมีองค์ประกอบเหมือนกันโดยไม่คำนึงถึงลำดับ
-
หากผลรวมขององค์ประกอบทั้งหมดของอาร์เรย์ที่หนึ่งและอาร์เรย์ที่สองมีค่าเท่ากัน
ตัวอย่างเช่น −
[3, 5, 6, 7, 7] and [7, 5, 3, 7, 6] are equal arrays [1, 2, 3, 1, 2] and [7, 2] are also equal arrays but [3, 4, 2, 5] and [2, 3, 1, 4] are not equal
มาเขียนโค้ดสำหรับฟังก์ชันนี้กัน −
ตัวอย่าง
const first = [3, 5, 6, 7, 7];
const second = [7, 5, 3, 7, 6];
const isEqual = (first, second) => {
const sumFirst = first.reduce((acc, val) => acc+val);
const sumSecond = second.reduce((acc, val) => acc+val);
if(sumFirst === sumSecond){
return true;
};
// do this if you dont want to mutate the original arrays otherwise use
first and second
const firstCopy = first.slice();
const secondCopy = second.slice();
for(let i = 0; i < firstCopy.length; i++){
const ind = secondCopy.indexOf(firstCopy[i]);
if(ind === -1){
return false;
};
secondCopy.splice(ind, 1);
};
return true;
};
console.log(isEqual(first, second)); ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็น -
true