Reputation: 73
I'm currently working on a personal project in JavaScript and have hit a major roadblock; I have 2 arrays, one for the letters of a sentence, and one that contains objects for informations.
I need to loop through the first array with all the letters, then loop through the second array to check if the letter
variable contains any of the data from the object
in my second arrays. The problem is that I do not know how to run these arrays at the same time, which results in an output like this, causes by the amount of indexes in array 1 multiplying with the amount in array 2:
Here is my code:
clearLookALikes: (string) => {
const mainArray = string.split('')
const replaceInfo = [
{
abuseLetter: 'È',
replacementLetter: 'E'
},
{
abuseLetter: 'É',
replacementLetter: 'E'
},
{
abuseLetter: 'Ë',
replacementLetter: 'E'
},
{
abuseLetter: 'Ê',
replacementLetter: 'E'
},
{
abuseLetter: 'Ē',
replacementLetter: 'E'
},
{
abuseLetter: 'Ē',
replacementLetter: 'e'
},
]
const newArray = []
for (const letter of mainArray) {
for (const object of replaceInfo) {
if (letter === object.abuseLetter) {
newArray.push(object.replacementLetter)
} else {
newArray.push(letter)
}
}
}
console.log(newArray)
const finishedProduct = newArray.join('')
console.log(finishedProduct)
}
Ideally, it replaces the letter as intended. Thanks for the help! I wonder if this is the right way to go about doing this, please feel free to give me feedback if I should do this differently.
Upvotes: 0
Views: 426
Reputation: 596
I am assuming that you are trying to replace certain abuseLetters
located in a string with replacementLetters
. To do this, you may not even want to split string
into an array, and just loop over replaceInfo
.
for (const obj of replaceInfo) {
string = string.replaceAll(obj.abuseLetter, obj.replacementLetter);
}
return string;
Upvotes: 1
Reputation: 16576
I'd recommend converting the replaceInfo
array to a map or object. The following code does that. Then, it iterates through the string and checks if there is a replacement letter in the object. If so, add that to the output string. If not, add the original letter.
const replaceInfo=[{abuseLetter:"È",replacementLetter:"E"},{abuseLetter:"É",replacementLetter:"E"},{abuseLetter:"Ë",replacementLetter:"E"},{abuseLetter:"Ê",replacementLetter:"E"},{abuseLetter:"Ē",replacementLetter:"E"},{abuseLetter:"Ē",replacementLetter:"e"}];
const replacementMap = replaceInfo.reduce((acc, el) => {
acc[el.abuseLetter] = el.replacementLetter;
return acc;
}, {});
function clearLookalikes(str) {
let final = "";
for(let i = 0; i < str.length; i++) {
if (replacementMap[str[i]] !== undefined) {
final += replacementMap[str[i]];
} else {
final += str[i];
}
}
return final;
}
console.log(clearLookalikes("thiÉefĒ"));
Upvotes: 1