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;
}
1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Im sorry, I don't really see what this does. could you please explain?
@Gabor Magyar: I edited my answer, to explain what is the function doing.
Note that IE (don't know which versions) does not support indexOf and lastIndexOf for arrays.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.