Any ideas to calculate min / max from array of strings?
JavaScript
x
2
1
var arr = ['aab','aac','aad','abx'];
2
So far i have considered to use .sort()
function depending max / min, and get first element of result.
But maybe you know better preforming solution?
EDIT: Array size is below 1k elements. By Min /max i meant alphabetic sort: first and last element.
Advertisement
Answer
Iterate through your list and update min and max in each iteration step
JavaScript
1
14
14
1
function getMinMax(arr) {
2
if (!arr) {
3
return null;
4
}
5
var minV = arr[0];
6
var maxV = arr[0];
7
for (a of arr) {
8
if (a < minV) minV = a;
9
if (a > maxV) maxV = a;
10
}
11
return [minV, maxV];
12
}
13
14
console.log(getMinMax(['abc', 'aaa', 'abb']));
It should be much faster than sort()
for large arrays. This algorithm is O(n) while sort()
is at least O(n log(n)).