ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่มีสองสตริงคือ str1 และ str2 ฟังก์ชันของเราควรคืนค่าเป็น "จริง" หากส่วนของอักขระ str1 สามารถจัดเรียงใหม่ให้ตรงกับ str2 ได้ มิฉะนั้นจะคืนค่าเป็น "เท็จ"
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const str1 = 'rkqodlw';
const str2 = 'world';
const canForm = (str1 = '', str2 = '') => {
if(str1.length < str2.length){
return false;
};
const res = str2.split('');
str1.split("").forEach(val => {
if(res.includes(val)){
res.splice(res.indexOf(val), 1);
};
});
return res.length === 0;
};
console.log(canForm(str1, str2)); ผลลัพธ์
ต่อไปนี้เป็นเอาต์พุตคอนโซล -
true