If you want to sort by year and quarter, you can achieve this using the following ES6 snippet. (It's also possible with ES5, but I prefer ES6)
input.map((obj, index) => obj.name.split("'").reverse().concat(index)).sort().map(arr => input[arr[2]]);
Let's break this down for better understanding
input.map((obj, index) => obj.name.split("'").reverse().concat(index))
The map() function creates a new array by calling a given function on each element in the original array.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
In our case, we split the "name" property of each object by the character "'", reverse the resulting array, and add the current index to it.
This operation results in an array like:
[
["2016", "Q1", 0],
["2016", "Q2", 1],
["2016", "Q3", 2],
["2015", "Q4", 3]
]
We then use .sort
,
The sort() method arranges the elements of an array and returns it. The default sorting order is based on Unicode points.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
After sorting, the array looks like:
[
["2015", "Q4", 3],
["2016", "Q1", 0],
["2016", "Q2", 1],
["2016", "Q3", 2]
]
Now, although the indexes are not ordered within, we can utilize this to establish order.
By another application of map, we retrieve the original object related to the stored index in our temporary arrays.
.map(arr => input[arr[2]]);
Upon executing this sequence, the resultant array will be structured as follows:
[
{
name: "Q4'2015",
y: 0
}, {
name: "Q1'2016",
y: 0
}, {
name: "Q2'2016",
y: 0
}, {
name: "Q3'2016",
y: 0
}
]
Give it a try with the provided demo:
let input = [
{
"name":"Q1'2016",
"y":0
},
{
"name":"Q2'2016",
"y":0
},
{
"name":"Q3'2016",
"y":0
},
{
"name":"Q4'2015",
"y":0
}
];
input = input.map((obj, index) => obj.name.split("'").reverse().concat(index)).sort().map(arr => input[arr[2]]);
console.log(input);
To replicate this process using ES5:
input.map(function(obj, index){
return obj.name.split("'").reverse().concat(index);
}).sort().map(function(arr){
return input[arr[2]];
});