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

การตรวจสอบว่าส่วนหนึ่งของสตริงจัดเรียงใหม่ได้เป็นอีกสตริงหนึ่งใน JavaScript


ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริง 2 สตริง str1 และ str2 ฟังก์ชันควรคืนค่า true หากส่วนหนึ่งของตัวอักษรใน str1 สามารถจัดเรียงใหม่ได้เป็น str2 มิฉะนั้นคืนค่า false

ตัวอย่าง

โค้ดตัวอย่างดังนี้:

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