在推送之前,Javascript检查2d数组上的第二项是否重复

时间:2016-12-16 21:58:40

标签: javascript arrays multidimensional-array

我有一个最大值:

var max = 666;
var check = 49;

在我的数学计算过程中,我将值对S推入像这样的二维数组

arr[i].push([a,b]);

但一切都很慢,我认为这是因为阵列非常庞大。我的arr就像这样

[ [ [ 1, 35 ],
    [ 2, 39 ],
    [ 3, 41 ],
    [ 4, 42 ],
    [ 5, 43 ],
    [ 6, 44 ],
    [ 7, 44 ],
    [ 8, 45 ],
    [ 9, 45 ],
    [ 10, 45 ],
    [ 11, 46 ],
    [ 12, 46 ],
    [ 13, 46 ],
    [ 14, 46 ],
    [ 15, 47 ],
    [ 16, 47 ],
    [ 17, 47 ],
    [ 18, 47 ],
    [ 19, 47 ],
    [ 20, 48 ],
    [ 21, 48 ],
    [ 22, 48 ],
    [ 23, 48 ],
    [ 24, 48 ],
    [ 25, 48 ],
    [ 26, 48 ],
    [ 27, 48 ],
    [ 28, 49 ],
    [ 29, 49 ],
    [ 30, 49 ]]

因为你可以看到第一个元素是渐进元素,第二个元素来自calc,我的想法是:

  1. 仅推送不存在第二个元素的对(最多一个)

  2. 如果第二个元素等于check var,我会推送第一个元素的max var,第二个元素的check var。停止

  3. 换句话说,这是预期的结果

    [ [ [ 1, 35 ],
        [ 2, 39 ],
        [ 3, 41 ],
        [ 4, 42 ],
        [ 5, 43 ],
        [ 7, 44 ],
        [ 10, 45 ],
        [ 14, 46 ],
        [ 19, 47 ],
        [ 27, 48 ],
        [ 666, 49 ]]
    

    有关如何尽可能快地制作它的任何想法?也许这不是问题所在,但我认为它越小越好,

    Ĵ

1 个答案:

答案 0 :(得分:0)

使用另一个数组来跟踪您已推送的值:

  if (!(b in already_pushed)) {
    if (b == check) {
      arr[i].push([max, b]);
      break;
    } else {
      already_pushed[b] = arr[i].length;
      arr[i].push([a, b]);
    }
  } else if (a > already_pushed[b]) {
    var index = already_pushed[b];
    arr[i][index][0] = a;
  }
}    

完整代码:



var max = 666;
var check = 49;

var input = [
  [1, 35],
  [2, 39],
  [3, 41],
  [4, 42],
  [5, 43],
  [6, 44],
  [7, 44],
  [8, 45],
  [9, 45],
  [10, 45],
  [11, 46],
  [12, 46],
  [13, 46],
  [14, 46],
  [15, 47],
  [16, 47],
  [17, 47],
  [18, 47],
  [19, 47],
  [20, 48],
  [21, 48],
  [22, 48],
  [23, 48],
  [24, 48],
  [25, 48],
  [26, 48],
  [27, 48],
  [28, 49],
  [29, 49],
  [30, 49]
];

var arr = [
  []
];
var already_pushed = [];
var i = 0;

for (var j = 0; j < input.length; j++) {
  var el = input[j];
  var a = el[0],
    b = el[1];
  if (!(b in already_pushed)) {
    if (b == check) {
      arr[i].push([max, b]);
      break;
    } else {
      already_pushed[b] = arr[i].length;
      arr[i].push([a, b]);
    }
  } else if (a > already_pushed[b]) {
    var index = already_pushed[b];
    arr[i][index][0] = a;
  }
}

console.log(arr);
&#13;
&#13;
&#13;