ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสองสตริง str1 และ str2 เป็นอาร์กิวเมนต์แรกและอาร์กิวเมนต์ที่สอง
ฟังก์ชันของเราควรจัดเรียง str1 ตามลำดับอักขระตามที่ปรากฏใน str2
ตัวอย่างเช่น หากอินพุตของฟังก์ชันคือ −
ป้อนข้อมูล
const str1 = 'coding'; const str2 = 'gncabdi';
ผลผลิต
const output = 'gncdio';
คำอธิบายผลลัพธ์
อักขระที่ปรากฏก่อนใน str2 จะถูกวางไว้ก่อน ตามด้วยอักขระที่ปรากฏขึ้นภายหลัง และสุดท้ายตามด้วยตัวอักษรที่ไม่อยู่ใน str2
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const str1 = 'coding';
const str2 = 'gncabdi';
const sortByOrder = (str1 = '', str2 = '') => {
str2 = str2.split('');
const arr1 = str1
.split('')
.filter(el => str2.includes(el))
.sort((a, b) => str2.indexOf(a) - str2.indexOf(b));
const arr2 = str1
.split('')
.filter(el => !str2.includes(el));
return arr1.join('') + arr2.join('');
};
console.log(sortByOrder(str1, str2)); ผลลัพธ์
gncdio