'How do I sort array of objects in descending order based on alphanumeric value in Javascript? [duplicate]
var ArrOfObj = [
{ name: "a", value: "BNG2000" },
{ name: "b", value: "BNG2001" },
{ name: "c", value: "CHN-4000" },
{ name: "d", value: "CHN-4004" }
]
I want to sort this array of object by descending order based on the value property.
Expected answer:
var ArrOfObj = [
{ name: "d", value: "CHN-4004" },
{ name: "c", value: "CHN-4000" },
{ name: "b", value: "BNG2001" },
{ name: "a", value: "BNG2000" }
]
Solution 1:[1]
You need a custom comparer function that will use the value property of your objects to make a descending alphabetic sort on your ArrOfObj.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
The comparer, in this demo I shared here, extracts the numeric part from string values and compares them based on how those 2 numbers are relative to each other so that the array will be sorted by value property in a descending manner.
BNG2000(as string) ->2000(as number)BNG2001(as string) ->2001(as number)CHN-4000(as string) ->4000(as number)CHN-4004(as string) ->4004(as number)
Sort order: 1: 4004, 2: 4000, 3: 2001, 4: 2000
var ArrOfObj=[
{name: "a", value:"BNG2000"},
{name: "b", value:"BNG2001"},
{name: "c", value:"CHN-4000"},
{name: "d", value:"CHN-4004"}
]
function customComparer(a, b){
const value_a = parseInt( getNumberPart(a.value) );
const value_b = parseInt( getNumberPart(b.value) );
if(value_a < value_b) return 1;
if(value_a > value_b) return -1;
return 0;
}
//returns the numeric part contained in subject string
function getNumberPart(subject){
let value = '';
const match = subject.match(/(\d+)/m);
if (match != null)
value = match[1];
return value;
}
ArrOfObj.sort( customComparer );
console.log(ArrOfObj);
/*
[
{
"name": "d",
"value": "CHN-4004"
},
{
"name": "c",
"value": "CHN-4000"
},
{
"name": "b",
"value": "BNG2001"
},
{
"name": "a",
"value": "BNG2000"
}
]
*/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
