Deleting the duplicate strings based on the ending characters - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of strings and deletes each one of the two strings that ends with the same character −

For example, If the actual array is −

const arr = ['Radar', 'Cat' , 'Dog', 'Car', 'Hat'];

Then we have to delete one and keep only one string ending with the same character in the array of distinct letters.

Example

Following is the code −

const arr = ['Radar', 'Cat' , 'Dog', 'Car', 'Hat'];
const delelteSameLetterWord = arr => {
   const map = new Map();
   for(let i = 0; i < arr.length; ){
      const el = arr[i];
      const last = el[el.length - 1];
      if(map.has(last)){
         arr.splice(i, 1);
      }else{
         i++;
         map.set(last, true);
      };
   }
};
delelteSameLetterWord(arr);
console.log(arr);

Output

This will produce the following output in console −

[ 'Radar', 'Cat', 'Dog' ]
raja
Updated on 30-Sep-2020 14:10:02

Advertisements