0

Similar to How to sort strings in JavaScript but I want to avoid sorting first, I just want the "largest" value of a string. For example

f(['Aa', 'B', 'C', 'Acd', 'Ace']) == 'C'

I am thinking it's something with .reduce like

const f = (a) => a.reduce(someFunctionGoesHere)

Where some function has an undefined check

UPDATE: Got it working but looks fugly. I wonder if I can reduce that function

const someFunctionGoesHere = (prev, current) => {
 if (!prev) {
 return current;
 }
 else if (prev.localeCompare(current) < 0) {
 return current;
 } else {
 return prev;
 }
};
const f = (a) => a.reduce(someFunctionGoesHere)
console.log(f(['Aa', 'B', 'C', 'Acd', 'Ace','CC']));

UPDATE: this works, one line, but looks quite ugly. I guess this is the best that can be done with Javascript itself.

const maxString = (a) => a.reduce((prev, current) => (!prev || prev.localeCompare(current) < 0) ? current : prev)
console.log(maxString(['Aa', 'B', 'C', 'Acd', 'Ace','CC']));
asked Sep 21, 2021 at 4:56
2
  • You already have reduce function. What do you want to achieve? Commented Sep 21, 2021 at 5:04
  • 1
    You can give a default value in array#reduce. Commented Sep 21, 2021 at 5:05

1 Answer 1

1

Indeed, reduce() will get you there:

const f = (array) => array.reduce((a, v) => v.localeCompare(a) > 0 ? v : a, '');
console.log(f(['Aa', 'B', 'C', 'Acd', 'Ace','CC']));

answered Sep 21, 2021 at 5:02

3 Comments

localeCompare returns a number. Your condition only false when v and a are equal.
@RickyMo Thanks, updated. Looks like I need more coffee :)
@RobbyCornelissen same here. I thought and proven again that sometimes articulating what you want makes the answer come out more naturally.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.