Computer >> Computer tutorials >  >> Programming >> Javascript

Delete elements in first string which are not in second string in JavaScript


We are required to write a JavaScript function that takes in two strings. Our function should return a newer version of the first string that contains only those elements that are present in the second string as well.

Note that the order of appearance of elements in the returned sting should not change, i.e., the order should be the same as it was in the first string.

Example

The code for this will be −

const str1 = 'abcdefgh';
const str2 = 'banana';
const deleteSelectively = (str1 = '', str2 = '') => {
   let strArr1 = str1.split('');
   const strArr2 = str2.split('');
   const map = {};
   strArr2.forEach(el => {
      map[el] = 1;
   });
   strArr1 = strArr1.filter(el => {
      return map.hasOwnProperty(el);
   });
   return strArr1.join('');
};
console.log(deleteSelectively(str1, str2));

Output

And the output in the console will be −

ab