Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Sorting one string by the order of second in JavaScript
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. Characters that appear first in str2 are placed first, followed by ones that come later, and finally followed by letters absent in str2.
Problem Example
For example, if the input to the function is:
Input
const str1 = 'coding'; const str2 = 'gncabdi';
Expected Output
gncdio
Output Explanation
Looking at str2 = 'gncabdi', the order is: g, n, c, a, b, d, i. From str1 = 'coding', we have characters: c, o, d, i, n, g. Sorting by str2's order: g (1st), n (2nd), c (3rd), d (6th), i (7th), and o (not in str2, goes last) = 'gncdio'.
Solution
The approach is to separate characters from str1 into two groups: those present in str2 and those absent, then sort the first group by str2's order.
const str1 = 'coding';
const str2 = 'gncabdi';
const sortByOrder = (str1 = '', str2 = '') => {
str2 = str2.split('');
// Characters from str1 that exist in str2, sorted by str2's order
const arr1 = str1
.split('')
.filter(el => str2.includes(el))
.sort((a, b) => str2.indexOf(a) - str2.indexOf(b));
// Characters from str1 that don't exist in str2
const arr2 = str1
.split('')
.filter(el => !str2.includes(el));
return arr1.join('') + arr2.join('');
};
console.log(sortByOrder(str1, str2));
gncdio
How It Works
The function works in three steps:
- Filter and Sort: Extract characters from str1 that exist in str2, then sort them by their position in str2 using indexOf()
- Collect Remaining: Get characters from str1 that don't exist in str2
- Combine: Concatenate the sorted characters with the remaining ones
Another Example
const sortByOrder2 = (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(sortByOrder2('hello', 'ole')); // Characters: h,e,l,l,o -> o,l,l,e,h
console.log(sortByOrder2('world', 'dlrow')); // Characters: w,o,r,l,d -> d,l,r,o,w
olleh dlrow
Conclusion
This solution efficiently sorts one string by another's character order using array filtering and sorting. The approach handles both matching and non-matching characters elegantly.
