Sorting one string by the order of second in JavaScript

JavascriptWeb DevelopmentFront End Technology

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
raja
Published on 22-Apr-2021 11:11:43
Advertisements