IT Man
IT Man

Reputation: 1036

Get max / min from array of strings (javascript)

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.

Upvotes: 6

Views: 19358

Answers (6)

rsinha
rsinha

Reputation: 763

To extend @Keith's answers.. if we want min or max only then reduce will be 1-liner.

const arr = ['aab', 'aac', 'aad', 'abx']
const min = arr.reduce((min, c) => c < min ? c : min) // 'aab'
const max = arr.reduce((max, c) => c > max ? c : max) // 'abx'

Upvotes: 8

Stratubas
Stratubas

Reputation: 3067

This is what I did (note that it mutates the original array):

const myArray = ['beta', 'alpha', 'zeta', 'delta'];
const min = myArray.sort()[0];
const max = myArray.reverse()[0];
console.log({ min, max });

Upvotes: 5

Thomas Sablik
Thomas Sablik

Reputation: 16454

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)).

Upvotes: 8

HMR
HMR

Reputation: 39250

You can use reduce in one pass but have to check what to return if the array is empty (currently returns undefined for both min and max)

const arr = [
  'aab',
  'aac',
  'aad',
  'abx',
];

console.log(
  arr.reduce(
    ([min, max], item) => [
      min.localeCompare(item) > 0
        ? item
        : min,
      max.localeCompare(item) < 0
        ? item
        : max,
    ],
    [arr[0], arr[0]],
  ),
);

Upvotes: 2

cross19xx
cross19xx

Reputation: 3487

Here are a few solutions to wrap your head around:

Min/max based on length

const output = arr.sort((a, b) => a.length - b.length);

Min/max as in alphabetical order

const output = arr.sort();

Extract the minimum and max

const max = arr.sort(() => 1)[0];

Upvotes: 4

Keith
Keith

Reputation: 24181

If you don't want to use a sort,.

Another option is to use Array.reduce to maintain the min & max values.

Below is a working snippet showing this.

ps. Your test data already had the min as the first element, and max as the last element, so I've altered the example array to have zzz, that of course would be max.

var arr = ['aab','aac','zzz','aad','abx'];

var ret = arr.reduce((a, v) => {
  a.min = a.min === null ? v :
    v.localeCompare(a.min) < 0 ? v : a.min; 
  a.max = a.max === null ? v : 
    v.localeCompare(a.max) > 0 ? v : a.max;
  return a; }, 
{min: null, max: null});

console.log(ret);

Upvotes: 5

Related Questions