Home > Enterprise >  Javascript apply sort(ascending order) for array of objects using key value
Javascript apply sort(ascending order) for array of objects using key value

Time:12-31

I have tried to sort the javascript array which is having "order" as the key but it is sorting only the parent array and inner objects are not sorting

Here is my sample code which have tried,

Sample JSON response:

   var MainObj = [
  {
    "title": "Merchant2",
    "order": 2,
    "subMenu": [
      {
        "subMenu1": "Initiate2",
        "order": 2
      },
      {
        "subMenu2": "Initiate1",
        "order": 1
      }
    ]
  },
  {
    "title": "Merchant1",
    "order": 1,
    "subMenu": [
      {
        "subMenu1": "Initiate2",
        "order": 2
      },
      {
        "subMenu2": "Initiate1",
        "order": 1
      }
    ]
  }
]

And below is the sort functionality,

    var sort = function (prop, arr) {
        prop = prop.split('.');
        var len = prop.length;
        
        arr.sort(function (a, b) {
            var i = 0;
            while( i < len ) {
                a = a[prop[i]];
                b = b[prop[i]];
                i  ;
            }
            if (a < b) {
                return -1;
            } else if (a > b) {
                return 1;
            } else {
                return 0;
            }
        });
        return arr;
    };
    
console.log(sort('order', MainObj));

But the expected output should be in the below way,

[
  {
    "title": "Merchant",
    "order": 1,
    "subMenu": [
      {
        "subMenu1": "Initiate1",
        "order": 1
      },
      {
        "subMenu1": "Initiate2",
        "order": 2
      },
      
    ]
  }
]

CodePudding user response:

You're not reaching into subMenu at all in your sort function. It's also unclear why you're splitting prop, and what the length has to do with anything, but based on your sample input and expected output, it can be much simpler:

const sort = (byProp, arr) =>
  arr.map((item) => ({
    ...item,
    subMenu: item.subMenu.sort((a, b) => a[byProp] - b[byProp])
  }))

console.log(
  JSON.stringify(
    sort('order', testInput), null, 2
  )
)

CodePudding user response:

To sort the inner objects of your array in ascending order based on the order property.

Try this

var MainObj = [{
    "title": "Merchant",
    "order": 1,
    "subMenu": [{
            "subMenu1": "Initiate2",
            "order": 2
        },
        {
            "subMenu2": "Initiate1",
            "order": 1
        }
    ]
}]

// sort function
var sort = function(prop, arr) {
    prop = prop.split('.');
    var len = prop.length;

    arr.forEach(function(obj) {
        obj.subMenu.sort(function(a, b) {
            var i = 0;
            while (i < len) {
                a = a[prop[i]];
                b = b[prop[i]];
                i  ;
            }
            if (a < b) {
                return -1;
            } else if (a > b) {
                return 1;
            } else {
                return 0;
            }
        });
    });

    return arr;
};

console.log(sort('order', MainObj));

Output:-

[
  {
    "title": "Merchant",
    "order": 1,
    "subMenu": [
      {
        "subMenu1": "Initiate1",
        "order": 1
      },
      {
        "subMenu1": "Initiate2",
        "order": 2
      },
      
    ]
  }
]
  • Related