数组 - 在序列中查找缺少的数字 [英] Arrays - Find missing numbers in a Sequence

查看:159
本文介绍了数组 - 在序列中查找缺少的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种简单的方法来循环(迭代)数组以找到序列中所有缺失的数字,该数组看起来有点像下面的数字。

I'm trying to find an easy way to loop (iterate) over an array to find all the missing numbers in a sequence, the array will look a bit like the one below.

var numArray = [0189459,0189460,0189461,0189463,0189465];

For上面的数组我需要 0189462 0189464 退出。

For the array above I would need 0189462 and 0189464 logged out.

更新:这是我在Soufiane的回答中使用的确切解决方案。

UPDATE : this is the exact solution I used from Soufiane's answer.

var numArray = [0189459, 0189460, 0189461, 0189463, 0189465];
var mia= [];

    for(var i = 1; i < numArray.length; i++) 
    {     
        if(numArray[i] - numArray[i-1] != 1) 
        {         
            var x = numArray[i] - numArray[i-1];
            var j = 1;
            while (j<x)
            {
                mia.push(numArray[i-1]+j);
                j++;
            }
        }
    }
alert(mia) // returns [0189462, 0189464]

更新

这是使用.reduce的整洁版本

Here's a neater version using .reduce

var numArray = [0189459, 0189460, 0189461, 0189463, 0189466];
var mia = numArray.reduce(function(acc, cur, ind, arr) {
  var diff = cur - arr[ind-1];
  if (diff > 1) {
    var i = 1;
    while (i < diff) {
      acc.push(arr[ind-1]+i);
      i++;
    }
  }
  return acc;
}, []);
console.log(mia);

推荐答案

如果您知道这些数字已经排序并且正在增加:

If you know that the numbers are sorted and increasing:

for(var i = 1; i < numArray.length; i++) {
    if(numArray[i] - numArray[i-1] != 1) {
           //Not consecutive sequence, here you can break or do whatever you want
    }
}

这篇关于数组 - 在序列中查找缺少的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆