7

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.

10
  • 1
    what is max and min in this case? Commented Feb 13, 2019 at 15:12
  • 2
    What do you consider the 'min' and 'max' of a string in this case? Commented Feb 13, 2019 at 15:12
  • 1
    Well if sorting would provide a meaningful answer then something like .localeCompare() could be used in a single pass. Commented Feb 13, 2019 at 15:13
  • 3
    The OP said he considered sort, so max / min one would assume is alpha sorted, first & last. Commented Feb 13, 2019 at 15:14
  • 1
    Iterate through your list and update min and max in each iteration step Commented Feb 13, 2019 at 15:14

6 Answers 6

11

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'
Sign up to request clarification or add additional context in comments.

1 Comment

If you have an array of integers encoded as strings, you can do this : const maxVal = chartVal.reduce((max, c) => parseInt(c) > parseInt(max) ? parseInt(c) : parseInt(max));
9

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

1 Comment

Note that this answer is case-sensitive: ['abigail', 'daniel', 'Denver'] will return 'Daniel' as the max string. To prevent that, use String.localeCompare() with a third parameter: if (a.localeCompare(minV, undefined, { sensitivity: 'base' }) < 0) minV = a; and if (a.localeCompare(maxV, undefined, { sensitivity: 'base' }) > 0) maxV = a; If you work in a language with accents, you might want to use { sensitivity: 'accent' } Reference : developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
6

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

Comments

5

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

3 Comments

sort will be o(nlog(n)), min/max is just o(n)
@Dee There is no sort here, did you mean that comment for the other answers?
yeah, i meant sorting shouldn't be an option
5

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];

7 Comments

While you're at it you should also show how to extract the minimum and maximum, since that's the question.
@FedericoklezCulloca. Noted
I see you modified the answer, but watch out, it's giving a TypeError for the argument to sort
Thank you for drawing my attention to it
Look, sorry if I'm being a pain in the neck, but that function you used to sort doesn't actually sort. Since OP said they meant lexicographic sorting you may as well just use const min = arr.sort()[0]; to extract the min. And you're still missing the max.
|
3

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]],
  ),
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.