3

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

Tushar
  • 85,780
  • 21
  • 159
  • 179
Opsional
  • 543
  • 4
  • 14
  • can i recommend using lodash/uniq? https://lodash.com/docs/4.17.4#uniq no reason to rewrite it. just reuse it – Dayan Moreno Leon Jun 23 '17 at 03:38
  • @DayanMorenoLeon `uniq` will remove the duplicate elements from the **array**, not the string itself. So, it cannot be used. – Tushar Jun 23 '17 at 03:41
  • Opsional - Your examples repeat the first two words only - do you want to remove words that repeat after that? Will the input array items always have the repeated words at the beginning, or might some already be just `'Category One Jackets'`? – nnnnnn Jun 23 '17 at 03:51
  • Hay nnnnnn, Yes. the array auto-generated. – Opsional Jun 23 '17 at 04:00
  • my bad i did not read the question properly. however with a little of split magic uniq could still be used `uniq(str.split(' ')).join(' ');` – Dayan Moreno Leon Jun 23 '17 at 04:08

2 Answers2

7

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.

Tushar
  • 85,780
  • 21
  • 159
  • 179
1

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(' ');
}
Tien Nguyen Ngoc
  • 1,555
  • 1
  • 8
  • 17