簡體   English   中英

理解用於排序數組的 javascript 解決方案

[英]Making sense of javascript solution for sorting an array

問題: 編寫一個 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) => ab); // 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM