Returning The Length Of The Shortest Word In A String In Javascript
Solution 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;
})
functionfindShort(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
constfindShort = str => Math.min(...str.split(' ').map(x => x.length))
console.log(findShort("The quick brown fox ju map"))
Solution 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:
functionfindShort(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:
functionfindShort(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
:
letfindShort = 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
.lengthconsole.log(findShort("in case users")) // 2console.log(findShort(" try set manually ")) // 3console.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:
letfindShort = 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")) // 2console.log(findShort(" try set manually ")) // 3console.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.
Post a Comment for "Returning The Length Of The Shortest Word In A String In Javascript"