Find the longest string in an array in JavaScript
Beginner · 3 min read
Given a list of country names, which one is the longest? From ["Australia", "Germany", "United States of America"], the answer is "United States of America". The same job comes up when you size a column in a table to fit its widest label, or pick the longest product name to test a layout.
In this tutorial you will write longestCountryName(names) with reduce, decide what happens with ties and empty lists, and see what .length really counts. You need to know arrays and functions. reduce is explained from the start.
reduce in one minute
reduce walks through an array and carries one value along, called the accumulator. On each item, your function gets the value so far and the current item, and returns the new value so far.
const total = [4, 2, 7].reduce((sum, n) => sum + n, 0);
console.log(total); // 13
The 0 at the end is the initial value, where the accumulator starts. If you leave it out, reduce starts with the first item instead and begins with the second.
.length counts every character
.length counts letters, spaces and punctuation alike. That is why the three-word name wins:
console.log('United States of America'.length); // 24
console.log('United States of America'.replace(/ /g, '').length); // 21
console.log('Australia'.length); // 9
The replace line removes the spaces, just to show they are part of the count.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
25 The longest country name
easy["Australia", "Germany", "United States of America"] should give "United States of America".
Stuck? Three hints, smallest first
- 1.
reducekeeping the longest so far is the direct route. - 2. Spaces count towards the length, which is why the three-word name wins.
- 3. Decide the tie rule and the empty-list result before writing the reduce.
Step 1: keep the longest so far
For the longest name, the accumulator is "the longest name seen so far". Compare it with each new name and keep whichever is longer:
const sample = ['Australia', 'Germany', 'United States of America'];
const longest = sample.reduce((best, name) => (name.length > best.length ? name : best));
console.log(longest); // 'United States of America'
There is no initial value here, so best starts as 'Australia', the first name. The ? : is the ternary operator: "if this, then that, otherwise the other".
Step 2: guard against an empty list
Without an initial value, reduce has nothing to start from on an empty array, and it throws:
try {
[].reduce((best, name) => (name.length > best.length ? name : best));
} catch (e) {
console.log(e.name); // 'TypeError'
}
So the function checks first. If the input is not an array, or it is empty, return null, meaning "no answer":
function longestCountryName(names) {
if (!Array.isArray(names) || names.length === 0) return null;
return names.reduce((longest, name) => (name.length > longest.length ? name : longest));
}
console.log(longestCountryName(sample)); // 'United States of America'
console.log(longestCountryName([])); // null
console.log(longestCountryName('Nigeria')); // null
Array.isArray is the reliable way to ask "is this an array?". A string has a length too, so checking length alone would let one through.
Step 3: decide the tie rule
'Chad', 'Cuba' and 'Fiji' all have four letters. Which one wins?
console.log(longestCountryName(['Chad', 'Cuba', 'Fiji'])); // 'Chad'
The comparison is >, "strictly longer". A name of the same length doesn't replace the current best, so the first one stays. If you wrote >=, the last one would win instead. Neither is wrong, but you should pick on purpose.
Step 4: return every name that ties
Sometimes you want all the winners. Find the biggest length first, then keep every name with that length:
function allLongest(names) {
if (!names.length) return [];
const max = Math.max(...names.map((n) => n.length));
return names.filter((n) => n.length === max);
}
console.log(allLongest(['Chad', 'Cuba', 'Fiji'])); // ['Chad', 'Cuba', 'Fiji']
console.log(allLongest(sample)); // ['United States of America']
names.map((n) => n.length) turns the names into their lengths. Math.max(...) takes the largest; the ... spreads the array into separate arguments.
Step 5: when length and characters differ
.length counts code units, the small pieces JavaScript stores text in. For most names, one character is one code unit:
const ivory = 'C\u00f4te d\u2019Ivoire';
console.log(ivory); // 'Côte d’Ivoire'
console.log(ivory.length); // 13
console.log([...ivory].length); // 13
\u00f4 is the letter ô and \u2019 is a curly apostrophe. Both fit in one code unit, so the two counts agree. Some characters, such as emoji, take two code units. For text like that, [...name].length counts the characters a person would count.
The full solution
The panel has longestCountryName and allLongest. It prints the sample's winner and each name's length, the tie result, the empty-list result, and the length with and without spaces. Press Run to see the output.
function longestCountryName(names) {
if (!Array.isArray(names) || names.length === 0) return null;
return names.reduce((longest, name) => (name.length > longest.length ? name : longest));
}
// Every name tied for longest.
function allLongest(names) {
if (!names.length) return [];
const max = Math.max(...names.map((n) => n.length));
return names.filter((n) => n.length === max);
}
const sample = ['Australia', 'Germany', 'United States of America'];
const withTie = ['Chad', 'Cuba', 'Fiji'];
console.log('longest:', longestCountryName(sample));
console.log('lengths:', sample.map((n) => `${n}=${n.length}`).join(', '));
console.log('a tie :', longestCountryName(withTie), '<- the first');
console.log('all tied:', allLongest(withTie));
console.log('empty :', longestCountryName([]));
console.log('--- length counts spaces ---');
console.log("'United States of America'.length =", 'United States of America'.length);
console.log('without spaces =', 'United States of America'.replace(/ /g, '').length);
Output
16 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 16 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test("the example in the question", longestCountryName(sample), 'United States of America');
test('one name is the longest', longestCountryName(['Nigeria']), 'Nigeria');
test('an empty list gives null', longestCountryName([]), null);
test('a non-array gives null', longestCountryName('Nigeria'), null);
test('a tie goes to the first', longestCountryName(withTie), 'Chad');
test('all tied names can be returned', allLongest(withTie), ['Chad', 'Cuba', 'Fiji']);
test('and a clear winner comes back alone', allLongest(sample), ['United States of America']);
test('spaces count towards the length', 'United States of America'.length, 24);
test('so ignoring them would change the answer', 'United States of America'.replace(/ /g, '').length, 21);
test('the returned name is one of the inputs', sample.includes(longestCountryName(sample)), true);
test('and no other name is longer', sample.every((n) => n.length <= longestCountryName(sample).length), true);
test('an empty string in the list does not win', longestCountryName(['', 'Chad']), 'Chad');
test('a list of only empty strings returns one', longestCountryName(['', '']), '');
test('accented names are measured by code unit', 'C\u00f4te d\u2019Ivoire'.length, 13);
test('which matches the character count here', [...'C\u00f4te d\u2019Ivoire'].length, 13);
test('so the two agree while every character fits in one code unit', 'C\u00f4te d\u2019Ivoire'.length === [...'C\u00f4te d\u2019Ivoire'].length, true);
Function 6 is the same reduce over words in a sentence; this is over a list that arrives already split, which is the easier half. Note the reduce here has no initial value, so it starts from the first element — that is why the empty-list guard has to come first, since reduce on an empty array with no initial value throws a TypeError.
.length counts UTF-16 code units, which for these names equals the character count — the last two assertions check that for Côte d'Ivoire. It would stop being true for a name containing a character outside the basic range, where [...name].length is the measure a person would agree with.
Common mistakes
- Calling
reduceon an empty array with no initial value. It throws aTypeError. Check for an empty list first. - Not deciding the tie rule.
>keeps the first of equal names,>=keeps the last. Choose one and know which. - Forgetting that spaces count.
.lengthincludes them, so removing spaces would change which name wins.
Try it yourself
- Write
shortestCountryName(names)by flipping one symbol in the comparison. - Change the tie rule so the last of equal names wins, and test it with
['Chad', 'Cuba', 'Fiji']. - Return an object with the name and its length, like
{ name: 'Chad', length: 4 }.