Reputation: 85
I have this string:
var text1 = "Ferrari Mercedes Ferrari Android iPhone LG iPhone iOS";
//text1 could be anything
I have these arrays:
var cars = ['Toyota', 'BMW', 'Ferrari', 'Mercedes'];
var phones = ['Nokia', 'Samsung', 'LG', 'iPhone'];
// cars values are fixed, but number of array could be increased
I want to replace each word in text1
with one of the words/values in an array that has a same value, example:
The word Ferrari in text1
will match one of Cars
values, so it will be replaced randomly either by BMW, Toyota, or Mercedes but not Ferrari nor one of the phones
values. (let say it was replaced randomly by BMW)
The second Ferrari word will also replaced by BMW
But the Mercedes word in text1
must not replaced by BMW and Mercedes
and also the same terms applied for words in text1
that categorized in phones
I expect the result could be something like:
text1 = "BMW Toyota BMW Android Nokia Samsung Nokia iOS";
What is the effective way to get this?
Upvotes: 1
Views: 409
Reputation: 1749
This is one way of doing it.
Here's the code:
var carOffset = Math.ceil(Math.random() * (cars.length-1));
var phoneOffset = Math.ceil(Math.random() * (phones.length -1));
var mapper = {};
for(var i = 0; i < cars.length; i++){
j = (i + carOffset) % cars.length;
mapper[cars[i]]=cars[j];
}
for(var i = 0; i < phones.length; i++){
j = (i + phoneOffset) % phones.length;
mapper[phones[i]]=phones[j];
}
var splitText = text1.split(' ');
var ansString = '';
var both = cars + phones;
for(var i = 0; i < splitText.length; i++){
var flag = 0;
for(var j = 0; j< both.length; j++){
if(splitText[i]===both[j]){
ansString += mapper[splitText[i]];
flag += 1;
}
}
if(flag === 0){
ansString += splitText[i];
}
ansString += ' ';
}
Upvotes: 2
Reputation: 1365
I would use this workflow:
Hope this helps.
Upvotes: 1