0

How to get the maximum value of this array with alphanumeric string in REACTJS?

I want to have an output of:

ABC113

Tried:

const arr = ['ABC111','ABC112', 'ABC113']
const latestArr = Math.max(arr)
console.log(latestArr)

2 Answers 2

1
  1. What makes these strings greater than one another, are they base 16 or something? The current format is non-numeric and cannot be compared as numbers. If they are base 16 make them numeric with parseInt('abc123',16)

If they are formatted as numbers in the array then you can get the max with Math.max like this:

const arr = [1,2,3];
const max = Math.max(...arr);
console.log(max);

If the values in the array are not in numerical format you could write a custom solution to compare values and get the max.

const arr = ['ABC111','ABC112', 'ABC113'];
const max = arr.reduce(function(prevMax, curVal) {
    // Replace this with logic needed to compare values
    return curVal > prevMax ? curVal : prevMax;
}, '0'); // Need to replace this base case with lowest possible value
console.log(max);

Sign up to request clarification or add additional context in comments.

Comments

0

If it is just a single dimension array of strings, could you just sort the array and get the last element. You will however have to consider case sensitivity if the values are not consistently uppercase. So if the array had 'abc110', that would show as the max. To make it case insensitive, you can just add a .map(ele => ele && ele.toUpperCase()) before the sort. If your array has empty values then you can use arr.filter to remove them first.

const arr = ['ABC111','ABC112', 'ABC113'];
const sortedarr = arr.map(ele => ele && ele.toUpperCase()).sort() ;
const maxValue = sortedarr[sortedarr.length -1];
console.log(maxValue);

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.