Reputation: 69
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
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
Reputation: 159
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