I have an array with a bunch of cars. However, the property Model contains unnecessary words that needs cleaning.
Here's the array:
const cars = [{
Id: 1,
Model: 'Transit 350 L3 Van'
},
{
Id: 2,
Model: 'Transit Custom 300 L2'
},
{
Id: 3,
Model: 'Transit Connect'
}
];
Here is a list of how the name should be:
const cleanNames = ['Transit Van', 'Transit Custom', 'Transit Connect']
I need some sort of function that can clean the model string and return it if there is a match. My issue is that using includes('Transit') gives match with all and includes('Transit van') does not match any. Note: words outside those in cleanNames are dynamic.
How do I approach this?
If you can change your cleanNames array to instead be an array of objects which match a regular expression to the replacement you want, it is easy enough to use that to match/replace the strings:
const cars = [{
Id: 1,
Model: 'Transit 350 L3 Van'
},
{
Id: 2,
Model: 'Transit Custom 300 L2'
},
{
Id: 3,
Model: 'Transit Connect'
},
{
Id: 4,
Model: 'Test'
}
];
const cleanNames = [
{find:'Transit.*Van',replace:'Transit Van'},
{find:'Transit Custom.*',replace:'Transit Custom'},
{find:'Transit Connect', replace: 'Transit Connect'}
]
const fixModel = (model, replacements) => {
var match = replacements.find(r => new RegExp(r.find).exec(model));
if(match)
return match.replace;
return model
}
const result = cars.map(car => ({
...car,
Model: fixModel(car.Model, cleanNames)
}));
console.log(result);
You can check if all the words of a "clean name" is included in a car's Model with this code:
if (cleanName.split(' ').every(word => car.Model.includes(word)) {
// This is a match
}
I am assuming cleanNames mean words without any numbers on it, for that you can use RegEX.
const cars = [{
Id: 1,
Model: 'Transit 350 L3 Van'
},
{
Id: 2,
Model: 'Transit Custom 300 L2'
},
{
Id: 3,
Model: 'Transit Connect'
}
];
cars.forEach(car => {
// regex to match words that contain numbers
car.Model = car.Model.replace(/\S*\d\S*/g, '');
// regex to remove extra spaces
car.Model = car.Model.replace(/\s+/g, ' ').trim();
})
console.log(cars)