Reputation: 75
I'm trying to find a way to sort an array that has dynamic keys without Lowdash. Any suggestions?
I'm trying to sort by the field unix_start
"chart": [
{
"Nov 24, 2020": {
"a": 1,
"b": 0,
"c": 0,
"unix_start": 1606194000,
"unix_end": 1606280400
}
},
{
"Nov 23, 2020": {
"a": 0,
"b": 2,
"c": 1,
"unix_start": 1606107600,
"unix_end": 1606194000
}
},
{
"Nov 22, 2020": {
"a": 0,
"b": 0,
"c": 0,
"unix_start": 1606021200,
"unix_end": 1606107600
}
},
}
Upvotes: 0
Views: 787
Reputation: 28414
You can use .sort
:
const chart = [
{
"Nov 24, 2020": {
"a": 1,
"b": 0,
"c": 0,
"unix_start": 1606194000,
"unix_end": 1606280400
}
},
{
"Nov 23, 2020": {
"a": 0,
"b": 2,
"c": 1,
"unix_start": 1606107600,
"unix_end": 1606194000
}
},
{
"Nov 22, 2020": {
"a": 0,
"b": 0,
"c": 0,
"unix_start": 1606021200,
"unix_end": 1606107600
}
},
]
const sortedArray = chart.sort((a,b) => {
const [valueOfA] = Object.values(a);
const [valueOfB] = Object.values(b);
return valueOfA.unix_start - valueOfB.unix_start;
});
console.log(sortedArray);
Upvotes: 5