问题
I have written code for determining the nth longest string in an array of strings. Below I have test cases listed from the Codewars kata.
Instructions: Implement the function longest(array,n) where you will be given an array of strings and then return the nth longest string in that array. e.g. arr = ['Hello','World','Codewars','Katas'] n = 3; should return 'World' because 'Codewars' length = 8 , 'Hello' length = 5, so that is the 2nd longest word and then 'World' (although also word length of 5, 'World' is after 'Hello' in the array). When words have the same lengths, treat them in the order in which they exist in the array. Array will never be empty and n > 0 always.
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');
I have passed all of the codewars test cases with exception to the last with the array ending in 'l'. My line of code for sortation seems to place the 'f' at the zeroth position for this test case and I don't understand why.
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
I cant seem to figure out why my sort function puts "f" at the zeroth position when the 'l' is added to the end of the string array.
回答1:
You use the built-in sort function, maybe this function change the algorithm of sort depending of your array ending up by not having the same behaviour with same length strings. And maybe even this is browser dependant.
I suggest you to change this by using a library with a determined sort function (quicksort, whatever...). And check if that happen again.
回答2:
Works fine on MSIE.
A quick test on Microsoft Internet Explorer (any version) gives the following results for the function you provided:
>> longest(['a','b','c','d','e','f','g','h','i','k'],1);
a,b,c,d,e,f,g,h,i,k
"a"
>> console.log(longest(['a','b','c','d','e','f','g','h','i','k','l'],1));
a,b,c,d,e,f,g,h,i,k,l
a
>> console.log(longest(['a','b','c','d','e','f','g','h','i','k','l',"m","n"],1));
a,b,c,d,e,f,g,h,i,k,l,m,n
a
p.s.: All non MS browsers have problems with the stability of sort().
来源:https://stackoverflow.com/questions/37006813/nth-longest-string-sortation