I want to sort the following list in the following order:
- first by object without any parent
- then by name
- by year
- by month
- related objects should come directly after by the criteria (2-4).
So what I want to achieve is basically a tree structure as a flat list.
This is what I've come up with until now, but can't figure out how to implement the parent relation.
function monthYearCheck(a, b) {
if(a.year < b.year) {
return -1;
} else if(a.year > b.year) {
return 1;
} else {
if(a.month < b.month) {
return -1;
} else if(a.month > b.month) {
return 1;
} else {
return 0;
}
}
}
var sortedArray = nonSortedArray.sort(function (a, b) {
if(a.name === b.name) {
return monthYearCheck(a, b);
} else if(a.name < b.name) {
return -1;
} else if(a.name > b.name) {
return 1;
}
});
This is the array before sorting:
[{
name: "Bottom",
id: 4,
parentId: 54,
month: 6,
year: 2016,
value: 16
},{
name: "Topp",
id: 12,
month: 6,
year: 2016,
value: 24
},{
name: "Middle",
id: 54,
parentId: 12,
month: 5,
year: 2016,
value: 14
},{
name: "Middle2",
id: 118,
parentId: 104,
month: 6,
year: 2016,
value: 4
},{
name: "Bottom2",
id: 5,
parentId: 54,
month: 5,
year: 2016,
value: 12
},{
name: "Topp",
id: 12,
month: 5,
year: 2016,
value: 12
},{
name: "Middle",
id: 54,
parentId: 12,
month: 6,
year: 2016,
value: 4
},{
name: "Topp2",
id: 104,
month: 5,
year: 2016,
value: 12
},{
name: "Bottom2",
id: 5,
parentId: 54,
month: 6,
year: 2016,
value: 2
}]
This is what I want to achieve:
[{
name: "Topp",
id: 12,
month: 5,
year: 2016,
value: 12
},{
name: "Topp",
id: 12,
month: 6,
year: 2016,
value: 24
},{
name: "Middle",
id: 54,
parentId: 12,
month: 5,
year: 2016,
value: 14
},{
name: "Middle",
id: 54,
parentId: 12,
month: 6,
year: 2016,
value: 4
},{
name: "Bottom",
id: 4,
parentId: 54,
month: 6,
year: 2016,
value: 16
},{
name: "Bottom2",
id: 5,
parentId: 54,
month: 6,
year: 2016,
value: 2
},{
name: "Bottom2",
id: 5,
parentId: 54,
month: 5,
year: 2016,
value: 12
},{
name: "Topp2",
id: 104,
month: 5,
year: 2016,
value: 12
},{
name: "Middle2",
id: 118,
parentId: 104,
month: 6,
year: 2016,
value: 4
}]
via Victor
No comments:
Post a Comment