Delete duplicate elements based on first letter – JavaScript


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

For example, If the actual array is −

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

Then, we have to keep only one string in the array, so one of the two strings starting with A should get deleted. In the same way, the logic follows for the letter J in the above array.

Let’s write the code for this function −

Example

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

Following is the output in the console −

[ 'Apple', 'Jack', 'Car' ]

Updated on: 14-Sep-2020

77 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements