Home > front end >  Angular Object Array Sorting
Angular Object Array Sorting

Time:02-10

Trying to sort the array of object, the property of the object contains alphanumeric values, Tried methods which didn't worked

test.sort((a,b)=> a.Code.localeCompare(b.Code)); test.sort((a,b)=> a.Code- b.Code);

let test = [{Code: '16', Color: "Red"},
      {Code: '54', Color: "Yellow"},
      {Code: '24', Color: "Yellow"},
      {Code: '1600', Color: "Blue"},
      {Code: '16a', Color: "Green"},
      {Code: '22', Color: "Yellow"},
      {Code: '23', Color: "Yellow"}];

 test.sort((a,b) =>  a.Code.localeCompare(b.Code));
 console.log(test);

getting output as

[{"Code": "16", "Color": "Red" },
{"Code": "1600","Color": "Blue"},
{"Code": "16a","Color": "Green"},
{"Code": "22","Color": "Yellow"},
{"Code": "23","Color": "Yellow"},
{"Code": "24","Color": "Yellow"},
{"Code": "54","Color": "Yellow"}]

How I can get the Expected output as

[{"Code": "16", "Color": "Red" },    
{"Code": "22","Color": "Yellow"},
{"Code": "23","Color": "Yellow"},
{"Code": "24","Color": "Yellow"},
{"Code": "54","Color": "Yellow"},
{"Code": "1600","Color": "Blue"},
{"Code": "16a","Color": "Green"}]

CodePudding user response:

You could check for numbers and move number to top and sort by numbers or by string.

let test = [{ Code: '16', Color: "Red" }, { Code: '54', Color: "Yellow" }, { Code: '24', Color: "Yellow" }, { Code: '1600', Color: "Blue" }, { Code: '16a', Color: "Green" }, { Code: '22', Color: "Yellow" }, { Code: '23', Color: "Yellow" }];

test.sort(({ Code: a }, { Code: b }) =>
    isFinite(b) - isFinite(a) ||
    a - b ||
    a.localeCompare(b)
);
console.log(test);
.as-console-wrapper { max-height: 100% !important; top: 0; }

CodePudding user response:

Try something as follows;

test.sort(a,b) => a.Code.localeCompare(b.Code, 'en', { numeric: true });

There is other possible solution if the above does not work as you expect.

Ref: Sort mixed alpha/numeric array

  • Related