With this array of objects:
[
{a: "1M"},
{a: "10D"},
{a: "1D"},
{a: "6Y"},
{a: "3D"}
]
how to sort this array to get this result:
[
"1D",
"3D",
"10D",
"1M",
"6Y"
]
With this array of objects:
[
{a: "1M"},
{a: "10D"},
{a: "1D"},
{a: "6Y"},
{a: "3D"}
]
how to sort this array to get this result:
[
"1D",
"3D",
"10D",
"1M",
"6Y"
]
You could take an object for getting a factor for the given unit and sort by value.
const
getValue = s => ({ D: 1, M: 30, Y: 365 })[s.slice(-1)] * s.slice(0, -1),
array = [{ a: "1M" }, { a: "10D" }, { a: "1D" }, { a: "6Y" }, { a: "3D" }],
result = array
.map(({ a }) => a)
.sort((a, b) => getValue(a) - getValue(b));
console.log(result);
Sorting by alphabet
const
array = [{ a: "1M" }, { a: "10D" }, { a: "1D" }, { a: "6Y" }, { a: "3D" }],
result = array
.map(({ a }) => a)
.sort((a, b) =>
a.slice(-1).localeCompare(b.slice(-1)) ||
a.slice(0, -1) - b.slice(0, -1)
);
console.log(result);