在循环阵列中找到缺失的数字

时间:2017-11-19 18:01:17

标签: javascript jquery arrays

我需要比较两个数组,并使用Javascript或jQuery找到缺少的数字。查找所有缺失的数字相对容易,但我需要将第一个数组看作是周期性的,这样我才能找到第二个数组中给定数字之间的单个缺失数字。

var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13]
var unsorted = [13,12,1,3]

如何比较两个数组并返回缺少的数字2 而不返回4-11

感谢任何帮助。谢谢!

使用更多信息进行编辑。比较两个阵列可能是错误的方法。这是我目前的代码:

// Function: Put numbers in order and return missing number from sequence
// Possible numbers are 1 through 13 max

var cyclical = [13,12,1,3] 
// Other examples, always only four numbers: [13,12,11,2] 1 is missing, [11,12,2,13] 1 is missing

var nonCyclical = [3,1,5,4]
// Another example: [7,3,5,4] 6 is missing

function absent(arr) {
    var mia = [],
        min = Math.min.apply('', arr),
        max = Math.max.apply('', arr);
    while (min < max) {
        if (arr.indexOf(++min) == -1) mia.push(min);
    }
    return mia;
}

var missingNumCyclical = absent(cyclical);
// Result: 2,4,5,6,7,8,9,10,11

var missingNum = absent(nonCyclical);
// Result: 2 (This is the desired result.)

1 个答案:

答案 0 :(得分:0)

var list1 = [1,2,3,4,5,6,7,8,9,10,11,12,13].sort((a, b) => a > b ? 1 : - 1)
var list2 = [13,12,1,3]
  // Sort the list
  .sort((a, b) => a > b ? 1 : - 1)
  .map((v, i, a) => {
    // Create a clone since shift is mutative
    const clone = [...list1]
    // Shift the array to the position of "v"
    clone.shift(clone.indexOf(v))
    // Slice the array to the position of v + 1
    const result = clone.slice(0, clone.indexOf(a[i + 1]))

    if (result.length === 1) {
      return result[0]
    }

    return undefined
  })
  .filter(n => n != null)