Reputation: 4599
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 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
}
]
}
]
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
},
]
}
]
Upvotes: 1
Views: 87
Reputation: 7747
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:
// sort an array of objects based on the value of those objects' `prop`
// creates a new array with [...] because `sort` mutates. this could be changed
// to use partial application if you'll have the same logic for other properties
// in the future.
const sortByProp = (prop, xs) =>
[...xs.sort((a, b) => a[prop] - b[prop])]
// sort the parent array based on some prop, and subMenu's array based on
// the same prop. if `subMenu` can possibly change down the line, that should be
// moved to an argument as well.
const sort = (prop, xs) =>
sortByProp(prop, xs.map((x) => ({
...x,
subMenu: sortByProp(prop, x.subMenu)
})))
// test
console.log(
JSON.stringify(
sort('order', testInput), null, 2
)
)
Upvotes: 4