1

We have this type of array and max represents the length of the word in the columns.

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

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

Because this array is really huge, what would be the most efficient way to do this?

puppeteer701
  • 1,225
  • 3
  • 17
  • 33
  • Have a look at http://stackoverflow.com/questions/13159594/simple-maximum-value-in-array-and-complexity-calculations – mccainz Oct 17 '14 at 12:54
  • 1
    You could try keeping the array sorted by word length whenever you insert new values. Then you'll only need to find the first/last value in the array. (depending on how it's sorted) – Grice Oct 17 '14 at 12:56
  • I don't think I get you – Amit Joki Oct 17 '14 at 12:58
  • JGrice makes a great comment regarding keeping sorted arrays, otherwise you are going to have to eat the whole meal. – mccainz Oct 17 '14 at 13:00
  • you cannot sort the arrays, because they represent in what order the values will be show. I need this, so I could somehow calculate the width of the column and create a table, because I will be using virtual scrolling. – puppeteer701 Oct 17 '14 at 13:02
  • this is not the same question as of Cerbrus. – puppeteer701 Oct 17 '14 at 13:04
  • Isn't it? You are going to have to eat the entire data structure (as stated you can't presort) so there is no algorithm efficiency to be had other than choosing the least costly comparison method. The linked SO question has a nice set of JSPerf tests with the accepted answer. – mccainz Oct 17 '14 at 13:12

1 Answers1

0
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);

Is there a more effective way?

Updated:

_maxs = [];

data.forEach(function (record) {
   record.forEach(function (vl, indx) {
      if (vl.length > (_maxs[indx]|| 0))
          _maxs[indx] = vl.length;
    })
});
puppeteer701
  • 1,225
  • 3
  • 17
  • 33