

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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 Questions & Answers
- Sorting string in reverse order in JavaScript
- Sorting string characters by frequency in JavaScript
- Sorting string in Descending order C++
- JavaScript - Check if array is sorted (irrespective of the order of sorting)
- JavaScript array sorting by level
- Is the second string a rotated version of the first string JavaScript
- Sorting an associative array in ascending order - JavaScript
- Sorting JavaScript object by length of array properties.
- Sorting array of Number by increasing frequency JavaScript
- Fetch Second minimum element from an array without sorting JavaScript
- Sorting objects by numeric values - JavaScript
- Sorting Integers by The Number of 1 Bits in Binary in JavaScript
- Sorting arrays by two criteria in JavaScript
- Sorting an array by date in JavaScript
- Sorting an array by price in JavaScript
Advertisements