
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort One String by the Order of Another in JavaScript
Problem
We are required to write a JavaScript function that takes in two strings, str1 and str2 as the first and the second argument.
Our function should sort str1 according to the order of characters as they appear in str2
For example, if the input to the function is −
Input
const str1 = 'coding'; const str2 = 'gncabdi';
Output
const output = 'gncdio';
Output Explanation
The characters that appear first in str2 are placed first followed by the ones that comes later and lastly followed by the letters absent in str2.
Example
Following is the code −
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));
Output
gncdio
Advertisements