Oashi
Oashi

Reputation: 69

How to get maximum value of alphanumeric of an array in reactjs

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)

Upvotes: 0

Views: 277

Answers (2)

Amox Cillin
Amox Cillin

Reputation: 53

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

Upvotes: 0

Malcolm
Malcolm

Reputation: 159

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

Upvotes: 1

Related Questions