【问题标题】:How to find the largest length for every column in a huge multidimensional Array如何在巨大的多维数组中找到每一列的最大长度
【发布时间】:2014-12-13 01:29:42
【问题描述】:

我们有这种类型的数组,max代表列中单词的长度。

var data = [
   ["1111", "44"],
   ["222", "55555"  ],
   ["33", "666"  ],
...
];

"1111".length > "222".length > "33".length,
"55555".length > "666".length > "44".length
var max -> [4,5];

因为这个数组真的很大,最有效的方法是什么?

【问题讨论】:

  • 您可以尝试在插入新值时保持数组按字长排序。然后你只需要找到数组中的第一个/最后一个值。 (取决于它的排序方式)
  • 我不明白你的意思
  • JGrice 对保持排序数组做出了很好的评论,否则你将不得不吃掉整顿饭。
  • 您无法对数组进行排序,因为它们表示值的显示顺序。我需要这个,所以我可以以某种方式计算列的宽度并创建一个表格,因为我将使用虚拟滚动。

标签: javascript arrays performance


【解决方案1】:
var data = [
   ['ABC', 'ABCD', 'ABCDEF', 'abcd', 'a', 'Abcdef', 'Abcderfg', 'A', 'ABC'],
   ['ABCD', 'ABC', 'ABCDEF', 'abc', 'AB', 'Abcdef', 'abcd', 'ABC', 'ABC'],
   ['Abcderfg', 'ABC', 'ABCDEFGH', 'abc', 'A', 'ABCDEF', 'abcd', 'AB', 'ABC']
];


var _maxs = [];  
var lenghtOfRow = data[0].length, _maxs = [];
for (var i=0; i<lenghtOfRow; i++) 
    _maxs.push(0);


data.forEach(function (record) {
   record.forEach(function (vl, indx) {
     if (vl.length > _maxs[indx])
         _maxs[indx] = vl.length;
   })
});

console.log(_maxs);

有没有更有效的方法?

更新:

_maxs = [];

data.forEach(function (record) {
   record.forEach(function (vl, indx) {
      if (vl.length > (_maxs[indx]|| 0))
          _maxs[indx] = vl.length;
    })
});

【讨论】:

  • 是的,这是不正确的。我的最大值:[8, 4, 8, 4, 2, 6, 8, 3, 3] 你的最大值: [8, 2: 6, 6: 8]
  • 我的答案使用有问题的数据输出[4,5][8, 2: 6, 6: 8] 来自哪里?
  • @MatjažJurečič 您可以通过在内部 forEach 中执行推零来跳过第一个循环:if (vl.length &gt; (_maxs[indx] || 0)) ...
  • 从你的回答中,如果我使用不同的数据。问题不仅在于这些数据,还在于不同的数据。
  • @MatjažJurečič:好的,很高兴你知道了。
猜你喜欢
  • 2023-02-17
  • 2018-09-25
  • 2017-06-19
  • 1970-01-01
  • 2016-08-24
  • 2022-11-01
  • 2019-06-13
  • 2018-04-11
  • 2012-04-20
相关资源
最近更新 更多