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 −

 Live Demo

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

Updated on: 22-Apr-2021

129 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements