- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Sorting one string by the order of second 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
- Related Articles
- Sorting string in reverse order in JavaScript
- Sorting string characters by frequency in JavaScript
- Sorting string in Descending order C++
- Sorting an associative array in ascending order - JavaScript
- JavaScript - Check if array is sorted (irrespective of the order of sorting)
- Sorting alphabets within a string in JavaScript
- Fetch Second minimum element from an array without sorting JavaScript
- JavaScript array sorting by level
- Is the second string a rotated version of the first string JavaScript
- Sorting numbers in ascending order and strings in alphabetical order in an array in JavaScript
- Finding sort order of string in JavaScript
- Sorting arrays by two criteria in JavaScript
- Sorting an array by date in JavaScript
- Sorting an array by price in JavaScript
- Sorting JavaScript object by length of array properties.

Advertisements