0

I wanted to sort this data based on number of employees using JavaScript

const companies = {
   'landwaves ltd': {employees: 1200, worth: '1.2m', CEO: 'Rajiv Bansal'},
   'colin & co': {employees: 200, worth: '0.2m', CEO: 'Sukesh Maheshwari'},
   'motilal biscuits': {employees: 975, worth: '1m', CEO: 'Rahul Gupta'},
   'numbtree': {employees: 1500, worth: '1.5m', CEO: 'Jay Kumar'},
   'solace pvt ltd': {employees: 1800, worth: '1.65m', CEO: 'Arvind Sangal'},
   'ambicure': {employees: 170, worth: '0.1m', CEO: 'Preetam Chawla'},
   'dis n dat': {employees: 540, worth: '1m', CEO: 'Mohit Sharma'},
}

I have tried with below function but it return as Array, is there any better way to solve this.

       sortProperties(obj, sortedBy, isNumericSort, reverse) {
        sortedBy = sortedBy || 1; // by default first key
        isNumericSort = isNumericSort || false; // by default text sort
        reverse = reverse || false; // by default no reverse

    var reversed = (reverse) ? -1 : 1;

    var sortable = [];
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            sortable.push([key, obj[key]]);
        }
    }
    if (isNumericSort)
        sortable.sort(function (a, b) {
            return reversed * (a[1][sortedBy] - b[1][sortedBy]);
        });
    else
        sortable.sort(function (a, b) {
            var x = a[1][sortedBy].toLowerCase(),
                y = b[1][sortedBy].toLowerCase();
            return x < y ? reversed * -1 : x > y ? reversed : 0;
        });
    return sortable; // array in format [ [ key1, val1 ], [ key2, val2 ], ... ]
}
1

1 Answer 1

0

If you sort something definitely the outcome should be an array which lists your sorted items in ascending or descending order. Even if you assigned the sorted array to a object with key, value pairs, it will become unsorted.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.