我已经编写了用于确定字符串数组中第n个最长字符串的代码。下面我列出了Codewars kata中列出的测试用例。第n个最长的字符串排序
说明:实现,你将获得一个字符串数组,然后数组中返回第n个最长的字符串函数最长(阵列,N)。例如arr = ['Hello','World','Codewars','Katas'] n = 3;应该返回'World',因为'Codewars'的长度= 8,'Hello'长度= 5,所以这是第二长的单词,然后'世界'(尽管也是5字长,'World'是'Hello'之后的数组)。当单词具有相同的长度时,请按照它们在数组中存在的顺序进行处理。数组永远不会是空的,并且n> 0总是。
Test.assertEquals(longest(['Hello','World','Codewars','Katas'],3),'World');
Test.assertEquals(longest(['Hello','World','Codewars','Katas'],4),'Katas');
Test.assertEquals(longest(['aa', 'bb', 'cc', 'dd', 'eee', 'b', 'f', 'ff', 'hhh', 'gggg'],4),'aa');
Test.assertEquals(longest(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k'],1),'a');
Test.assertEquals(longest(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k','l'],1),'a');
我已经通过了所有的测试codewars例例外,最后在“L”结尾的数组。我的分拣代码行似乎将'f'放在第0个位置,我不明白为什么。
function longest(arr, n) {
arrLength = [];
arr.sort(function(a, b){return b.length - a.length});
console.log(arr);
arr.forEach(function(numArray){
return arrLength.push(numArray.length);
});
return arr[n-1];
}
console.log(longest(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k'],1));
// Sorted Array: ["a", "b", "c", "d", "e", "f", "g", "h", "i", "k"]
// returns a
console.log(longest(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k', 'l'],1));
// Sorted Array: ["f", "a", "c", "d", "e", "b", "g", "h", "i", "k", "l"]
// returns f
我似乎无法弄清楚,为什么当“L”被添加到字符串数组结束我的排序函数把“F”在零的位置。
您的排序功能是测量长度。为什么你会期望任何特定的订单,当所有的项目是相同的长度? – bhspencer
非常感谢您的帮助。我真的很感谢你对我的问题的贡献... –