1

Got string, need to delete same words from there.

Here is my code. I tried to split string into array and then sort but it didn't work. It didn't even go through my if. I would like to hear your advice and maybe working code :)

  var str = "I wont go anywhere as soon as I wont go there";
    var array = str.split(" ");
    document.getElementsByTagName('p')[0].innerHTML = str;
    document.getElementsByTagName('p')[1].innerHTML = array;
    document.getElementsByTagName('button')[0].onclick = function () {
            for (var i = 0; i < array.length; i++) {
                if (array[i] == array[i + 1]) {
                    array.splice(i, 1);
                }
            }
            document.getElementsByTagName('p')[2].innerHTML = array;
        }
freginold
  • 3,946
  • 3
  • 13
  • 28
ttmcswg
  • 67
  • 1
  • 8
  • 2
    Possible duplicate of [Javascript how to remove text from a string](https://stackoverflow.com/questions/10398931/javascript-how-to-remove-text-from-a-string) – Gustavo Magalhães Jul 17 '17 at 20:00

4 Answers4

1

If you like one-lines try this

var reducedString  = array.reduce(function(out, s) {
    return out.indexOf(s) == -1 ? out + ' ' + s : out;
},'').substring(1);

or in ES6

var reducedString = array.reduce( (out, s) => out.indexOf(s) == -1 ? out + ' ' + s : out);
Jarek Kulikowski
  • 1,399
  • 8
  • 9
0

You can use an ES6 Set with the spread syntax after splitting the sentance:

const str = "I wont go anywhere as soon as I wont go there";
const unique = [...new Set(str.split(' '))].join(' ');

console.log(unique);

In ES5 you can use Array#reduce with a dictionary object.

var str = "I wont go anywhere as soon as I wont go there";

var dict = Object.create(null); // creates an empty object, without inherited properties and methods
var unique = str.split(' ').reduce(function(arr, w) {
  if(!dict[w]) {
    arr.push(w);
    dict[w] = true;
  }
  
  return arr;
}, []).join(' ');

console.log(unique);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

You can just replace the substring you are searching for

var ret = "data-123".replace('data-','');
console.log(ret);
0

Your problem is that you don't check every array element with every other array element.

Your code:

for (var i = 0; i < array.length; i++) {
            if (array[i] == array[i + 1]) {
                array.splice(i, 1);
            }
        }

Just checks array elements in sequence.

Try:

for (var i = 0; i < array.length; i++) {
     for(var j = 0; j < array.length; j++){
          if (array[i] == array[j] && i != j) {
                array.splice(i, 1);
            }
     }
}
Abbas Akhundov
  • 562
  • 6
  • 12