Lrn*_*Lru 1 javascript arrays sorting function
说明:此函数将接受两个参数。第一个参数应该是一个数组。第二个参数应该是一个数字。您的函数必须执行以下操作:
首先将输入数组(第一个参数)按字母顺序排序。
输入数组排序后,返回一个新数组数组,它是输入数组的前 N 个元素,其中 N 是函数的第二个参数的值:
function getFirstAmountSorted(inputArray, numberOfThings) {
// Step 1 - sort inputArray alphabetically
let bucket = input.sort();
let citrus = bucket.slice(0, 1);
return citrus;
// Step 2 - create an array which contains the first items of the sorted array -
// the number of items is provided in the second argument
// Step 3 - return the new array you created in step 2
}
Run Code Online (Sandbox Code Playgroud)
但是当我用 调用这个函数时(['third, 'second', 'third'], 2),它只在它应该返回时返回第一个'first', 'second'。我究竟做错了什么?
我没有在函数中使用第二个参数,因为我不知道把它放在哪里:')
按照Karan Singh在评论中的建议,我尝试了这段代码并且它有效。我已经把它变成了一个社区维基来反映这一点。
我会尽力解释为什么我认为它有效。
因此,在此函数中,numberOfitems 可以根据您希望从数组中调用的内容而有所不同。他们希望它适用于由变量 N 表示的任何数字。
拼图要求您按字母顺序排列。当您对 inputArray 进行排序时,您可以实现这一点。
接下来它要求您返回一个新的数组数组,它是输入数组的前 N 个元素,其中 N 是函数的第二个参数的值:
当你切片时,你会得到一个带有开始和结束的新数组。您希望它从 0 开始并在 2 结束。不包括结尾,因此它将为您提供数组中的元素 0 和 1,换句话说,第一个和第二个参数。
因此,当您使用函数在 const 中进行测试时:
getFirstAmountSorted(['cat', 'apple', 'bat'], 2);
Run Code Online (Sandbox Code Playgroud)
您将按字母顺序对它们进行排序,然后是一个元素为 0 和 1 的新数组。
如果您编写了相同的函数并像这样调用它
const newArray = getFirstAmountSorted(['cat', 'apple', 'bat'], 3);
Run Code Online (Sandbox Code Playgroud)
你会得到一个带有 0、1 和 2 的新输出。这里的目标是有一个灵活的 N,而不是一个特定的 [0,1] 等。
function getFirstAmountSorted(inputArray, numberOfItems) {
let bucket = inputArray.sort();
let citrus = bucket.slice(0, numberOfItems);
return citrus;
}
Run Code Online (Sandbox Code Playgroud)