Delete every one of the two strings that start with the same letter in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of strings and deletes every one of the two strings that start with the same letter.

For example, If the actual array is −

const arr = ['Apple', 'Jack' , 'Army', 'Car', 'Jason'];

Then we have to delete and keep only one string in the array distinct letters, so one of the two strings starting with A should get deleted and the same should the one with J.

Example

The code for this will be −

const arr = ['Apple', 'Jack' , 'Army', 'Car', 'Jason'];
const delelteSameLetterWord = arr => {
   const map = new Map();
   arr.forEach((el, ind) => {
      if(map.has(el[0])){
         arr.splice(ind, 1);
      }else{
         map.set(el[0], true);
      };
   });
};
delelteSameLetterWord(arr);
console.log(arr);

Output

The output in the console −

[ 'Apple', 'Jack', 'Car' ]
raja
Published on 14-Oct-2020 11:22:54
Advertisements