Any ideas to calculate min / max from array of strings?
var arr = ['aab','aac','aad','abx'];
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
function getMinMax(arr) { if (!arr) { return null; } var minV = arr[0]; var maxV = arr[0]; for (a of arr) { if (a < minV) minV = a; if (a > maxV) maxV = a; } return [minV, maxV]; } 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)).