Remove duplicate words in array elements

227
June 23, 2017, at 1:00 PM

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

Answer 1

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.

Answer 2

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(' ');
}
READ ALSO
multiple nav-tabs collapse href are in loop but lapsing at the end

multiple nav-tabs collapse href are in loop but lapsing at the end

dynamic nav-tabs collapse href are in loop but lapsing at the end the first collection of tabs have the effect of javascript and the rest is not

156
Reading JSON file to HTML through AJAX/JS

Reading JSON file to HTML through AJAX/JS

Hey stackoverflow community, I'm having trouble displaying my JSON fileI have been using AJAX/JS/Jquery functions to try and display my content

225
Iterating over a list of django created objects in Javascript, is it possible? Template language in Javascript

Iterating over a list of django created objects in Javascript, is it possible? Template language in Javascript

My site can't run a successful for-loop created in django for a list model that I have sent to a pageI was going based off of Derek's answer in this stackoverflow question and some other things I found

256
Render links in Datatables issue

Render links in Datatables issue

I can't seem to figure out what my issue is with rendering this link through the Datatables Jquery

260