freeCodeCamp/curriculum/challenges/chinese/10-coding-interview-prep/rosetta-code/longest-string-challenge.md

2.1 KiB

id title challengeType forumTopicId dashedName
5e6dd14192286d95fc43046e Longest string challenge 5 385275 longest-string-challenge

--description--

In this challenge, you have to find the strings that are the longest among the given strings.

--instructions--

Write a function that takes an array of strings and returns the strings that have a length equal to the longest length.

--hints--

longestString should be a function.

assert(typeof longestString == 'function');

longestString(["a", "bb", "ccc", "ee", "f", "ggg"]) should return a array.

assert(Array.isArray(longestString(['a', 'bb', 'ccc', 'ee', 'f', 'ggg'])));

longestString(["a", "bb", "ccc", "ee", "f", "ggg"]) should return ["ccc", "ggg"]'.

assert.deepEqual(longestString(['a', 'bb', 'ccc', 'ee', 'f', 'ggg']), [
  'ccc',
  'ggg'
]);

longestString(["afedg", "bb", "sdccc", "efdee", "f", "geegg"]) should return ["afedg", "sdccc", "efdee", "geegg"].

assert.deepEqual(
  longestString(['afedg', 'bb', 'sdccc', 'efdee', 'f', 'geegg']),
  ['afedg', 'sdccc', 'efdee', 'geegg']
);

longestString(["a", "bhghgb", "ccc", "efde", "fssdrr", "ggg"]) should return ["bhghgb", "fssdrr"].

assert.deepEqual(
  longestString(['a', 'bhghgb', 'ccc', 'efde', 'fssdrr', 'ggg']),
  ['bhghgb', 'fssdrr']
);

longestString(["ahgfhg", "bdsfsb", "ccc", "ee", "f", "ggdsfg"]) should return ["ahgfhg", "bdsfsb", "ggdsfg"].

assert.deepEqual(
  longestString(['ahgfhg', 'bdsfsb', 'ccc', 'ee', 'f', 'ggdsfg']),
  ['ahgfhg', 'bdsfsb', 'ggdsfg']
);

longestString(["a", "bbdsf", "ccc", "edfe", "gzzzgg"]) should return ["gzzzgg"].

assert.deepEqual(longestString(['a', 'bbdsf', 'ccc', 'edfe', 'gzzzgg']), [
  'gzzzgg'
]);

--seed--

--seed-contents--

function longestString(strings) {

}

--solutions--

function longestString(strings) {
    var mx = 0;
    var result = []
    strings.forEach(function (e) {
        if (e.length > mx) {
            mx = e.length
            result = [e]
        } else if (e.length == mx)
            result.push(e)
    })

    return result
}