I am currently trying to create a function that looks for the shortest word in a string of words.
Problem: I am getting the following error
TypeError: Cannot read property ‘length’ of undefined
at findShort
at Test.describe._
at /runner/frameworks/javascript/cw-2.js:152:11
at Promise._execute
at Promise._resolveFromExecutor
at new Promise
at Object.describe
at /home/codewarrior/index.js:24:10
at /home/codewarrior/index.js:28:5
at Object.handleError
Here is my code
findShort("turns out random test cases are easier than writing out basic ones");
function findShort(s){
let array = s.split(" ");
let shortestWord = array[0];
for (i = 0; i < array.length; i++) {
let str = array[i + 1];
if (shortestWord.length > str.length) {
shortestWord = str.length;
}
}
return shortestWord;
}
asked Sep 28, 2018 at 20:04
I see two problems:
-
The line
let str = array[i + 1]
is going to result inundefined
on the last run of your loop. That’s because on the last run,i
is one less than the array length, soi + 1
is therefore out of the array bounds. To compensate for that, consider changing the loop condition toi < array.length - 1
. -
Second, you are assigning the word length to the
shortestWord
variable, where I think you meant to assign the word itself to that.
Taking those two changes into account, you could modify your code like so:
function findShort(s) {
let array = s.split(" ");
let shortestWord = array[0];
for (i = 0; i < array.length - 1; i++) { // -1 here to compensate for the +1 on the next line.
let str = array[i + 1];
if (shortestWord.length > str.length) {
shortestWord = str; // Just assign the word itself to this variable, not the length of it.
}
}
return shortestWord;
}
const result = findShort("turns out random test cases are easier than writing out basic ones");
console.log(result);
answered Sep 28, 2018 at 20:15
CRiceCRice
29.2k4 gold badges58 silver badges70 bronze badges
1
I believe this is a more concise way of doing what you’re looking for:
console.log(findShort("turns out random test cases are easier than writing out basic ones"));
function findShort(s){
let input = s;
let array = input.split(" ");
var shortest = array.reduce((shortestWord, currentWord) => {
return currentWord.length < shortestWord.length ? currentWord : shortestWord;
}, array[0]);
return shortest;
}
https://jsfiddle.net/02z5oyh1/
CRice
29.2k4 gold badges58 silver badges70 bronze badges
answered Sep 28, 2018 at 20:15
Joe FitzsimmonsJoe Fitzsimmons
1,0331 gold badge7 silver badges22 bronze badges
1
I’m back with more CodeWars katas! I took a break to focus on other things for a while, but now my mind is refreshed and ready to solve some more coding challenges.
CodeWars challenges solved
1) Sum of two lowest positive integers (7 kyu)
2) Ones and Zeros (7 kyu)
3) Shortest Word (7 kyu)
Kata 1: Sum of two lowest positive integers
Instructions
Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 positive integers. No floats or non-positive integers will be passed.
For example, when an array is passed like [19, 5, 42, 2, 77]
, the output should be 7
.
[10, 343445353, 3453445, 3453545353453]
should return 3453455
.
Breaking down the problem with P.R.E.P.
Parameters
The function expects one parameter: an array of 4 or more
positive integers.
Returns
The function should return one value: the sum of the 2 lowest numbers in the array.
Examples
The following test cases are provided by CodeWars.
[5, 8, 12, 19, 22], 13
[15, 28, 4, 2, 43], 6
[3, 87, 45, 12, 7], 1
[23, 71, 33, 82, 1], 24
[52, 76, 14, 12, 4], 16
Enter fullscreen mode
Exit fullscreen mode
The array is the parameter passed to the function and the number is the integer that should be returned from the function.
Pseudo code
See pseudo code section for each solution
Solution 1: Sorting the array
Pseudo code
1) Create a new array with sorted numbers from smallest to largest.
2) Return the sum of the first two numbers in the array.
Enter fullscreen mode
Exit fullscreen mode
Solution
function sumTwoSmallestNumbers(numbers) {
const sortedNums = numbers.sort((a, b) => a - b);
return sortedNums[0] + sortedNums[1];
}
Enter fullscreen mode
Exit fullscreen mode
Notes
The .sort()
array method — as the name suggests — sorts the elements of the array and returns the sorted array. It can receive an optional comparison function — like in the solution above — to sort the array in a specific manner. In this solution, passing it the comparison function of a - b
will sort the numbers from lowest value to highest value.
Solution 2: Using array destructuring
This solution is similar to the one above but uses a different method of selecting the numbers inside the array called array destructuring. When working with arrays, it can be a very useful method to work with the elements inside the array.
function sumTwoSmallestNumbers(numbers) {
const [a, b] = numbers.sort((a, b) => a - b);
return a + b;
}
Enter fullscreen mode
Exit fullscreen mode
Notes
Instead of declaring a variable storing the complete sorted array, a new array is declared holding only two values: a
and b
, which will automatically hold the values of the first two numbers in the sorted array.
Solution 3: One-liner
The following solution combines the two lines of code from solution 1 into a single line of code.
function sumTwoSmallestNumbers(numbers) {
return numbers.sort((a, b) => a - b)[0] + numbers[1];
}
Enter fullscreen mode
Exit fullscreen mode
Notes
The .sort()
array method does not actually make a copy of the array but mutates the original array. So instead of storing the sorted array in a new variable like in solution 1, the elements can be selected directly from the array passed to the argument once it has been sorted.
Kata 2: Ones and Zeros
Instructions
Given an array of ones and zeroes, convert the equivalent binary value to an integer.
Eg: [0, 0, 0, 1]
is treated as 0001
which is the binary representation of 1
.
Examples:
Testing: [0, 0, 0, 1] ==> 1
Testing: [0, 0, 1, 0] ==> 2
Testing: [0, 1, 0, 1] ==> 5
Testing: [1, 0, 0, 1] ==> 9
Testing: [0, 0, 1, 0] ==> 2
Testing: [0, 1, 1, 0] ==> 6
Testing: [1, 1, 1, 1] ==> 15
Testing: [1, 0, 1, 1] ==> 11
Enter fullscreen mode
Exit fullscreen mode
However, the arrays can have varying lengths, not just limited to 4
.
Breaking down the problem with P.R.E.P.
Parameters
The function expects one parameter: an array of ones and zeroes of any given length.
Returns
The function should return one value: the integer representation of the binary inside the array.
Examples
All test cases provided can be found in the instructions.
Pseudo code
See pseudo code section for each solution
Solution 1: Parsing a binary string
Pseudo code
1) Convert array to string.
2) Convert the string to an integer by parsing it.
3) Return the integer.
Enter fullscreen mode
Exit fullscreen mode
Solution
const binaryArrayToNumber = arr => parseInt(arr.join(''), 2);
Enter fullscreen mode
Exit fullscreen mode
Notes
1) Unlike the solutions from kata 1, all the solutions in this kata use the ES6 arrow function syntax.
2) The .join()
array method is used to convert the array into a string. It concatenates the array elements into a string using either commas to separate the array values inside the string (default) or by using the separator specified inside the parenthesis. In this case all the numbers are joined together without a comma or any spaces between the numbers.
3) The parseInt()
function receives two parameters: the string to parse and the radix that will be used for parsing — in our case 2 for binary.
Solution 2: Reducing the value with math
Pseudo code
1) Start with a sum (accumulator) value of 0.
2) Multiple the accumulator by 2 and add 1 each iteration of the loop.
3) Return the accumulated value.
Enter fullscreen mode
Exit fullscreen mode
Solution
const binaryArrayToNumber = arr => {
return arr.reduce((acc, cur) => acc * 2 + cur, 0);
}
Enter fullscreen mode
Exit fullscreen mode
Notes
1) The .reduce()
array method is used to «loop over» an array, executing a callback function on each element of the array. The callback function has access to both the current element in the array and the previous value, which is an accumulation of all the executed calculations combined (often called the accumulator). This sum or accumulator value can be passed a default value, which is specified after the comma (in this case the default value is 0
).
2) Since the .()reduce
method essentially loops over each item in the array, it takes more time to execute than the first solution, which has the same execution time regardless of the array length. While the difference in time will be rather small because of how fast execution time is nowadays, it is still something to take into account, especially when dealing with longer arrays. Solutions that can operate in constant time — meaning independent of the array length — are more favorable than solutions that take more time depending on array length.
No third solution for this kata will be provided. There are technically other ways to solve this challenge, but they are much more difficult to understand and/or have significant downsides, which make them less desirable as a solution.
Kata 3: Shortest Word
Instructions
Simple, given a string of words, return the length of the shortest word(s).
String will never be empty and you do not need to account for different data types.
Breaking down the problem with P.R.E.P.
Parameters
The function expects one parameter: a string of words.
Returns
The function should return one value: the length of the shortest word in the string.
Examples
The following test cases are provided by CodeWars.
("bitcoin take over the world maybe who knows perhaps"), 3
("turns out random test cases are easier than writing basic ones"), 3
("Let's travel abroad shall we"), 2
Enter fullscreen mode
Exit fullscreen mode
The string of words between the parenthesis is the string passed to the function, followed by the number that should be returned from the function.
Pseudo code
See pseudo code section for each solution
Solution 1: Using a for loop
Pseudo code
1) Create an array of the words contained in the string.
2) Declare a new variable with a value of the first word's length.
3) Loop over each word in the array.
4) Check if word's length is smaller than the value of the variable.
5) If it is, set the word's length as the new value of the variable.
6) Return the variable's value.
Enter fullscreen mode
Exit fullscreen mode
Solution
function findShort(s){
const arr = s.split(' ');
let shortest = arr[0].length;
for (let i = 0; i < arr.length; i++) {
if (arr[i].length < shortest) {
shortest = arr[i].length;
}
}
return shortest;
}
Enter fullscreen mode
Exit fullscreen mode
Notes
The .split()
array method is used to convert the string into an array of words. The string is split into substrings each time a space is encountered, which is not included in the substrings.
Solution 2: Sorting the words by word length
This solution uses a very similar approach as solution 3 of kata 1, except with one extra step (turning the string into an array) and the sorting is done based on word length.
Solution
function findShort(s){
return s.split(' ')
.sort((a, b) => a.length - b.length)[0].length;
}
Enter fullscreen mode
Exit fullscreen mode
Notes
Just like in the 3rd solution of kata 1, the first element in the array is selected once the array has been sorted. We then get the length of that word since we don’t want to return the word itself, but its length.
Solution 3: Finding the min in an array of word lengths
Pseudo code
1) Create an array of the words contained in the string.
2) Create another array containing the length of each word.
3) Find the lowest number in that array.
4) Return it.
Enter fullscreen mode
Exit fullscreen mode
Solution
function findShort(s){
return Math.min(...s.split(' ').map(word => word.length));
}
Enter fullscreen mode
Exit fullscreen mode
Notes
1) The .map()
array method is used to create a new array by looping over the original array and executing a function on each element inside the array. An arrow function is used in this solution, which can be read as for each word in the array, return the length of the word
.
2) The Math.min()
function receives numbers as its parameter and returns the number with the lowest value out of those numbers. The numbers passed to it have to be separated by a comma and cannot be contained inside an array.
3) The spread operator (…array) is used to turn the array of numbers into numbers that can be passed to the Math.min()
function.
What solution did you implement?
What solution did you find the most elegant?
What solution did you have trouble understanding?
Let me know, I’d love to hear from you!
I hope you found this article helpful.
Connect with me on …
Twitter
GitHub
$begingroup$
So the kata/problem was: «Simple, given a string of words, return the length of the shortest word(s).»
Example test: findShort(«Bitcoin will maybe save the world»)
And my solution was:
function findShort(s){
// convert string to array
const strArr = s.split(' ');
// loop through array and find length
const lengthOfWords = strArr.map(string => {
return (string.length);
})
// output length of shortest string
return Math.min(...lengthOfWords);
}
asked Oct 27, 2021 at 17:52
$endgroup$
2
$begingroup$
As far as implementation goes, it looks generally good to me (though arguably you should be splitting on any whitespace character, not just spaces). However I do feel that the function name (findShort
) is unclear, and additionally those comments do not offer any benefit. Indeed, the second one is perhaps even misleading.
answered Nov 5, 2021 at 13:46
PetePete
4113 silver badges6 bronze badges
$endgroup$
Today I try to solve the algorithm problem of codewars.
Description
Simple, given a string of words, return the length of the shortest word(s).
String will never be empty and you do not need to account for different data types.
Example
-
findShort(“i want to travel the world writing code one day”) -> 1
-
findShort(“Lets all go on holiday somewhere very cold”) -> 2
-
findShort(“lets talk about Java the best language”) -> 3
Code
- split() : returns array of strings computed by splitting.
import jav.util.Arrays;
public class Kata {
public static int findShort(String s) {
# Codewars COC 정책으로 인하여 코드 제거
return min;
}
}
Written on December 11, 2018
Codewars Js Shortest Word With Code Examples
Hello everyone, in this post we will look at how to solve the Codewars Js Shortest Word problem in the programming language.
function findShort(s) { var arr = s.split(' '); var smallest = arr[0]; for (var i = 0; i < arr.length; i++) { if (arr[i].length < smallest.length) { smallest = arr[i]; } } return smallest.length; }
Utilizing a wide range of different examples allowed the Codewars Js Shortest Word problem to be resolved successfully.
How do I get the shortest word in Javascript?
javascript find shortest word in string
- const findShort = str => { // Convert string into an array of individual words:
- const arr = str. split(‘ ‘); // Sort array in ascending order:
- arr. sort((a, b) => a. length – b. length); // Return the first (shortest) element in the array:
- return arr[0]; };
What is the longest and shortest word?
In English, the shortest words are four letters long. In some other languages, we use words of only two characters. The longest words are 17-18 letters – for example, “environmentalists” and “unenthusiastically”. The longest word in any language so far is in Portuguese – ‘caracteristicamente’.
What is shortest word in English?
The shortest word is a. Some might wonder about the word I since it consists of one letter, too. In sound, a is shorter because it is a monophthong (consists of one vowel), while I is a diphthong. Both do consist of one letter in the English writing system, and in most fonts I is the narrowest letter.
How do you return the shortest word in a string?
“How to find the shortest word in a string JavaScript” Code Answer’s
- const findShort = str => {
- // Convert string into an array of individual words:
- const arr = str. split(‘ ‘);
- // Sort array in ascending order:
- arr. sort((a, b) => a. length – b.
- // Return the first (shortest) element in the array:
- return arr[0];
- };
How do you find the shortest word in an array?
find shortest string in array java
- public static String smallest(String words[]) {
- if (words == null || words. length
- return “”;
- }
- String smallest = words[0];
- for (int i = 1; i
- if (words[i]. length()
- smallest = words[i];
What word is longer than Pneumonoultramicroscopicsilicovolcanoconiosis?
Longest word in English
How many letters are in Pneumonoultramicroscopicsilicovolcanoconiosis?
forty-five letters
What word is 189 819 letters long?
methionylthreonylthreonylglutaminylalanyl… You’ll notice there’s an ellipsis here, and that’s because this word, in total, is 189,819 letters long, and it’s the chemical name for the largest known protein, titin.28-May-2021
Is there a word with all 26 letters?
An English pangram is a sentence that contains all 26 letters of the English alphabet. The most well known English pangram is probably “The quick brown fox jumps over the lazy dog”. My favorite pangram is “Amazingly few discotheques provide jukeboxes.”
What is the longest S word?
16-letter words that start with s
- sociolinguistics.
- sesquicentennial.
- sphygmomanometer.
- semiprofessional.
- sonoluminescence.
- stereomicroscope.
- sternoclavicular.
- strongyloidiasis.