0

This is what I've been trying, but something is wrong with the last part, can sy please tell me whats wrong, or show me an other method of doing this. Thanks in advance.

function removeSpaces(string) {
  var str = string.replace(/^\s*|\s*$/g,'')
  str = str.replace(/[^a-z|A-z|\r\n]/g,'');
  while (str.indexOf("\r\n\r\n") >= 0) {
    str = str.replace(/\r\n\r\n/g, "\r\n");
  }
  words = str.split("\r\n");
  var i = 0;
  var j = 0;
  for (i = 0; i < words.length; i++) {
    for (j = i; j < words.length; j++) {
      if ((i != j) && (words[i] == words[j])) {
        words.splice(j,1);
        j--;
      }
    }
  }
  str = words.join("\r\n");
  return str;
}
Hubert Kario
  • 21,314
  • 3
  • 24
  • 44
Gabor Magyar
  • 926
  • 2
  • 9
  • 20
  • This question is similar to this one: http://stackoverflow.com/questions/6940103/how-do-i-make-unique-array/6940165#6940165 – F-A Aug 10 '11 at 12:38

1 Answers1

1

You could use the filter function. The filter function of an array is returning an array containing elements which pass to a certain filter.

var isLastElement = function(element, index, array){
    return (index == array.lastIndexOf(element));
};
words = words.filter(isLastElement);

In this example, the filter function goes through the elements of the initial array ad add this element to the new array only if isLastElement(element, elementIndex, initArray) return true.
The isLastElement function returns true only if the element is not present a second time in the end of the array.

F-A
  • 643
  • 3
  • 10
  • Im sorry, I don't really see what this does. could you please explain? – Gabor Magyar Aug 10 '11 at 12:43
  • @Gabor Magyar: I edited my answer, to explain what is the function doing. – F-A Aug 10 '11 at 13:02
  • 1
    Note that IE (don't know which versions) does not support `indexOf` and `lastIndexOf` for arrays. – Felix Kling Aug 10 '11 at 13:03
  • @Gabor Magyar: You're welcome. Glad it helped you. However as Felix Kling said, it might not work on all browser, you can have a look at the link I posted as a comment to your question for other solutions. – F-A Aug 10 '11 at 14:00