Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Deleting the duplicate strings based on the ending characters - JavaScript
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 duplicates and keep only one string ending with the same character. In this case, 'Cat', 'Car', and 'Hat' all end with 't', 'r', and 't' respectively, so we need to remove duplicates based on the last character.
How It Works
The algorithm uses a Map to track which ending characters we've already seen. When we encounter a string with a duplicate ending character, we remove it from the array using splice().
Example
const arr = ['Radar', 'Cat', 'Dog', 'Car', 'Hat'];
const deleteSameLetterWord = arr => {
const map = new Map();
for(let i = 0; i < arr.length; ){
const el = arr[i];
const last = el[el.length - 1].toLowerCase();
if(map.has(last)){
arr.splice(i, 1);
}else{
i++;
map.set(last, true);
}
}
};
console.log("Original array:", arr);
deleteSameLetterWord(arr);
console.log("After removing duplicates:", arr);
Original array: [ 'Radar', 'Cat', 'Dog', 'Car', 'Hat' ] After removing duplicates: [ 'Radar', 'Cat', 'Dog' ]
Alternative Approach Using filter()
Here's a functional approach that doesn't modify the original array:
const arr = ['Radar', 'Cat', 'Dog', 'Car', 'Hat'];
const removeDuplicateEndings = arr => {
const seen = new Set();
return arr.filter(str => {
const lastChar = str[str.length - 1].toLowerCase();
if (seen.has(lastChar)) {
return false;
}
seen.add(lastChar);
return true;
});
};
const result = removeDuplicateEndings(arr);
console.log("Original array:", arr);
console.log("Filtered result:", result);
Original array: [ 'Radar', 'Cat', 'Dog', 'Car', 'Hat' ] Filtered result: [ 'Radar', 'Cat', 'Dog' ]
Key Points
- The first approach modifies the original array in-place using
splice() - The second approach returns a new array without modifying the original
- Both methods convert the last character to lowercase for case-insensitive comparison
- When using
splice(), we don't increment the index when removing an element
Conclusion
Both approaches effectively remove strings with duplicate ending characters. Choose the first method to modify the array in-place, or the second for a functional programming approach that preserves the original array.
