Reputation: 543
I have a small problem with replace words in array. Ok, this my array:
var words = ['Category One Category One Clothes', 'Category One Category One Jackets'];
I want final result like this:
var result = ['Category One Clothes', 'Category One Jackets'];
Try with this method, but not working Removing duplicate strings using javascript
Upvotes: 3
Views: 1463
Reputation: 1555
You can use this. I hope it will work for you.
function unique(array) {
return $.grep(array, function (el, index) {
return index == $.inArray(el, array);
});
}
var words = ['Category One Category One Clothes', 'Category One Category One Jackets'];
var result = [];
for (i = 0; i < words.length; i++) {
arr = unique(words[i].split(' '));
result[i] = arr.join(' ');
}
Upvotes: 1
Reputation: 87203
For the given input, this should work.
words.map(w => w.replace(/([\w\s]+)\1+/, '$1'))
var words = ['Category One Category One Clothes', 'Category One Category One Jackets'];
var result = words.map(w => w.replace(/([\w\s]+)\1+/, '$1'));
console.log(result);
The regex ([\w\s]+)
will match the words/spaces and \1+
will match the same word again.
Upvotes: 7