理解javascript解决方案对数组进行排序



问题:编写一个JavaScript函数,该函数将获取存储的数字数组,并找到倒数第二和倒数第二的数字。

不确定此解决方案如何工作:

function Second_Greatest_Lowest(arr_num) {
arr_num.sort(function(x, y) {
return x - y;
});
var uniqa = [arr_num[0]];
var result = [];
for (var j = 1; j < arr_num.length; j++) {
if (arr_num[j - 1] !== arr_num[j]) {
uniqa.push(arr_num[j]);
}
}
result.push(uniqa[1], uniqa[uniqa.length - 2]);
return result.join(',');
}

我想我理解循环中发生的事情,但我不确定为什么稍后将uniqa[1]推入结果数组时需要这样做。他们不是在做同样的动作吗?

var numbers = Array(5, 5,6,3,1,67,8,4,2,421,5,1,1,0,0)
function task(numbers)
{
// Get the unique items
numbers = numbers.filter((el, index, arr) => arr.indexOf(el) == index);
// Sort them
numbers = numbers.sort((a, b) => a-b);

// Take the ones you want
return Array(numbers[1], numbers.splice(-2)[0])
}
console.log("Targets: ", task(numbers))

几乎正确,只有您需要对数组进行的验证大于1。

function getSecondLowerAndHighest(arr){
//make the array me unique numbers
arr = [...new Set(arr)];
//array from minimum to maximum
arr.sort((x,y) => x - y);
const lower = arr[1];
//array from maximum to minimum
arr.reverse();
const high = arr[1];
return {lower, high};
}

const myFunction = (arr) => {
arr = arr
.filter((v, i, a) => a.indexOf(v) === i) // filter unique values
.sort() // sort if needed

return [arr[1], arr[arr.length-2]]
}
const [ secondLowest, secondHighest ] = myFunction([6, 3, 6, 5, 2, 1, 2, 4])
console.log(secondLowest, secondHighest)

最新更新