I have an array of similar kind of strings like the list of landmarks :
["AB Street", "A B Street", "AB Street XE", "AB Street X", "AB Street(XE)"]
Each of these represent a single landmark "AB Street".
I have tried different approaches, found a way for removing extra spaces and special characters but not able to figure out how to cut short the extraneous entries with extended names which anyways lead to same string.
Code snippet for removing spaces and special characters :
var landmarks = ["AB Street", "A B Street", "AB Street XE", "AB Street X", "AB Street(XE)"];
var formattedLandmarks = [];
landmarks.sort();
landmarks.forEach(function(location) {
var key = location && location.toLowerCase();
key = key.replace(/[.\/-]*/g, "");
key = key.replace(/\(.*\)/i, "");
key = key.replace(/[0-9, _-]*$/, "");
key = key.replace(/[ \t]+/g, " ");
key = key.toString().trim();
key = key.charAt(0).toUpperCase() + key.slice(1);
formattedLandmarks.push(key);
});
console.log(formattedLandmarks);
I expect the algorithm to return output as array with only one entry :
["AB Street"]
It will be really great if someone can help out with the best possible approach and algorithm to achieve the expected output, be it through RegExp or some other way.
Any help is appreciable.
1 Answer 1
You can try something like this:
Logic
- Sort the array in ascending order
- Set initial value to be blank
- Loop over and check if current value has previous. If not, then push it in array.
Note: You are comparing parsed values, so you should sort based on these parsed values only.
var array = ["AB Street", "A B Street", "AB Street XE", "AB Street X", "AB Street(XE)"];
var regex = /[^a-z]/gi;
var final = [];
array.sort(function(item1, item2){
var _a = item1.replace(regex,"");
var _b = item2.replace(regex,"");
return _a > _b? 1: _a < _b ? -1: 0;
}).reduce(function(currentItem, nextItem) {
var _p = currentItem.replace(regex, "");
var _c = nextItem.replace(regex, "");
if (_c.indexOf(_p)<0 || !currentItem) {
final.push(nextItem);
}
return nextItem;
}, "")
console.log(final)
Reference
- Array.sort
- Array.reduce
- Regex 101 for understanding regex.
5 Comments
Explore related questions
See similar questions with these tags.
[ "ABStreet", "AB Street XQ", "AB Street XEA", "AB Street(XE)"]- how should look the expected result for it?similar_text()which has apparently been ported to JS here. Not sure if this is the right algorithm for your needs, though.