- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can part of a string be rearranged to form another string in JavaScript
Problem
We are required to write a JavaScript function that takes in two strings, str1 and str2. Our function should return true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.
Example
Following is the code −
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));
Output
Following is the console output −
true
Advertisements