Returning the length of the shortest word in a string in JavaScript [duplicate]

我的梦境 提交于 2021-01-28 15:01:35

问题


I'm trying to write a function that returns the length of the shortest word in a string. It only works some of the time and I can't seem to figure out why.

function findShort(s) {
  const stringArray = s.split(" ");

// Compares the length of two words, then moves to the next till complete.
// Returns the words in order of length 
  const orderedArray = stringArray.sort((a, b) => {
    return a.length > b.length;
  })
  //returns the length of the first word(0 index of array) 
  return orderedArray[0].length;

}

回答1:


You need to return a number from sort() not a boolean. The sort() function should be:

const orderedArray = stringArray.sort((a, b) => {
   return a.length - b.length;
})

function findShort(s) {
  const stringArray = s.split(" ");
  const orderedArray = stringArray.sort((a, b) => {
    return a.length - b.length
  })
  return orderedArray[0].length;

}
console.log(findShort("The quick brown fox ju map"))

You don't need to sort() the whole array just use map() to get array of lengths and then pass it to Math.min

const findShort = str => Math.min(...str.split(' ').map(x => x.length))
console.log(findShort("The quick brown fox ju map"))



回答2:


Using your function it seems to me you have not addressed the edge case where the sentence starts or ends with empty string and not provided the sort function with a numeric value (vs boolean one). For example:

function findShort(s) {
  const stringArray = s.split(" ");  // <-- no .trim()
  const orderedArray = stringArray.sort((a, b) => {
    return a.length - b.length;  // - instead of >
  })
  return orderedArray[0].length;
}

console.log(findShort(" try set manually "))  // 0 is wrong here

If we address this via String.trim you get:

function findShort(s) {
  const stringArray = s.trim().split(" ");
  const orderedArray = stringArray.sort((a, b) => {
    return a.length - b.length;
  })
  return orderedArray[0].length;
}

console.log(findShort(" try set manually "))  // 3 is correct now!

Using Array.sort is one way to achieve this and it would more or less something like this in its ES6 variant:

let findShort = s => s
  .trim()            // <-- making sure we remove any spaces at start and end
  .split(' ')        // <-- get the words from the sentence
  .sort((a, b) => a.length - b.length)[0]  // <-- sort & take the 1st element
  .length

console.log(findShort("in case users"))       // 2
console.log(findShort(" try set manually "))  // 3
console.log(findShort("A great story"))       // 1

You could also write your own function which would be more performant overall since it would not need to iterate over the array multiple times (split/sort or split/map/Math.min etc).

Something like this:

let findShort = str => {
  let t = '', r = str, s = str.trim()
  for(let i=0; i<s.length; i++) {
    !!s[i].trim()
     ? t += str[i]
     : (r = t.length < r.length ? t : r, t='')
  }
  r = t.length < r.length ? t : r
  return r.length
}

console.log(findShort("in case users"))       // 2
console.log(findShort(" try set manually "))  // 3
console.log(findShort("A great story"))       // 1

Where you would loop one time only and keep track of the last word. You would keep checking if the new one is shorter during each for loop iteration by simply checking the lengths. If it is then that becomes your last word etc.



来源:https://stackoverflow.com/questions/56815010/returning-the-length-of-the-shortest-word-in-a-string-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!