Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - How to sort array of object by 3 different attributes type? (String, Integer, Boolean)

I have array of object:

var a = [
  {"name": "BBB", "no": 2, "size1": [3], "size2": null },
  {"name": "AAA", "no": 5, "size1": null, "size2": [1] },
  {"name": "BBB", "no": 1, "size1": [2], "size2": null },
  {"name": "AAA", "no": 4, "size1": null, "size2": [1] },
  {"name": "BBB", "no": 1, "size1": null, "size2": [1] },
  {"name": "AAA", "no": 5, "size1": [2], "size2": null },
  {"name": "BBB", "no": 2, "size1": null, "size2": [1] },
];

I want to sort it like this, Sort By name ascending, and then no ascending and then by size1 if it not null.

At first, I can sort it by name and no, but after that I don't know how to sort by size1 or size2. It should sorted by size1 first if it is not null. Here is my code to sort

function sortObject(arrayObjects){
    arrayObjects.sort(function(a,b){
        if(a.name=== b.name){
            return (a.no - b.no);
        } else if(a.name > b.name){
            return 1;
        } else if(a.name < b.name){
            return -1;
        }
    });
}

Expected result

var a = [
  {"name": "AAA", "no": 4, "size1": null, "size2": [1] },
  {"name": "AAA", "no": 5, "size1": [2], "size2": null },
  {"name": "AAA", "no": 5, "size1": null, "size2": [1] },
  {"name": "BBB", "no": 1, "size1": [2], "size2": null },
  {"name": "BBB", "no": 1, "size1": null, "size2": [1] },
  {"name": "BBB", "no": 2, "size1": [3], "size2": null },
  {"name": "BBB", "no": 2, "size1": null, "size2": [1] },
]
like image 264
David Vincent Avatar asked Aug 31 '18 10:08

David Vincent


People also ask

How do you sort an array of objects in JavaScript?

To sort an array of objects in JavaScript, use the sort() method with a compare function. A compare function helps us to write our logic in the sorting of the array of objects. They allow us to sort arrays of objects by strings, integers, dates, or any other custom property.


1 Answers

You would have to compare no in your first if:

function sortObject(arrayObjects){
    arrayObjects.sort(function(a,b){
        if (a.name=== b.name) {
            if (a.no === b.no) {
                // Determines which size to use for comparison
                const aSize = a.size1 || a.size2;
                const bSize = b.size1 || b.size2;

                return (aSize[0] - bSize[0]);
            }
            return (a.no - b.no);
        } else if (a.name > b.name) {
            return 1;
        } else if (a.name < b.name) {
            return -1;
        }
    });
}
like image 73
Telokis Avatar answered Nov 15 '22 00:11

Telokis