-2
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" }
]
pilchard
  • 12,414
  • 5
  • 11
  • 23
fallen1202
  • 13
  • 5

1 Answers1

0

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"
  }
]
*/
Diego D
  • 6,156
  • 2
  • 17
  • 30
  • Hi Diego, Thanks for replying. Here I want to sort only based on numbers in value property. Example, In the value we have "CHN-4000" , I don't want to consider "CHN" take only "4000" number and sort. is there any way to do it? – fallen1202 May 04 '22 at 03:03
  • I edited my answer so that the comparer now extracts the numeric part from the string and use this to make the comparison (in numeric terms not in string terms) – Diego D May 04 '22 at 06:40