1

How do you splice spaces from an array?

var lengthOfLastWord = function(s) {
  let lastWordResults;
  let sentence = s.split(' ');
  let theLastWord = s.split(' ').pop();
  if (theLastWord.length < 1) {
    console.log('WE GOT A PROBLEM - ok time to delete some stuff, here is sentence now: ' + sentence)
    for(i=0; i < sentence.length; i++) {
      if(sentence[i] == '') {
        sentence.splice(i, 1);
      }
    }
    console.log('trimmed the crap, here is sentence now: ' + sentence)
    console.log('okay so now the last word should be: ' + sentence.pop())
  }
  lastWordResults = `The last word is "${theLastWord}" with length ${theLastWord.length}.`
  // console.log(lastWordResults) 
};

lengthOfLastWord('    god.   I hate   leetcode    why  ');

Basically all I need to do is echo the last word of a sentence and it's length, like this:

The last word is "why" with length 3.

The catch is that I need to make it so that if it's all spaces it still needs to work and get the last word no matter what. So my thinking is that if the last "word" is just " " we make a new array without all the spaces and just get the last one with .pop()

How can I remove a specific item from an array?

To remove an element of an array at an index i:

array.splice(i, 1);

 let theLastWord = s.split(' ').pop();
  if (theLastWord.length < 1) {
    console.log('WE GOT A PROBLEM - ok time to delete some stuff, here is sentence now: ' + sentence)
    for(i=0; i < sentence.length; i++) {
      if(sentence[i] == '') {
        sentence.splice(i, 1);
      }
    }
    console.log('trimmed the crap, here is sentence now: ' + sentence)
    console.log('okay so now the last word should be: ' + sentence.pop())

what you'll notice however is that the output of the .pop() of the now modified array is still a space/blank, why is this happening?

I also changed my approach slightly like this answer:

Removing all space from an array javascript

and did this:

var lengthOfLastWord = function(s) {
  let lastWordResults;
  let sentence = s.split(' ');
  let theLastWord = s.split(' ').pop();
  if (theLastWord.length < 1) {
    console.log('WE GOT A PROBLEM - ok time to delete some stuff, here is sentence now: ' + sentence)
    sentence.map(str => str.replace(/\s/g, ''));
    console.log('trimmed the crap, here is sentence now: ' + sentence)
    console.log('okay so now the last word should be: ' + sentence.pop())
  }
  lastWordResults = `The last word is "${theLastWord}" with length ${theLastWord.length}.`
  // console.log(lastWordResults) 
};

lengthOfLastWord('    god.   I hate   leetcode    why  ');

But sadly it's still blank.

How do you splice spaces out of the result of a .split() operation?

kawnah
  • 3,204
  • 8
  • 53
  • 103

0 Answers0