'Sorting "day" "week" "month" and "year"
I have an array of objects from an API
[
{path: 'image', location: 'LOCATION_1', time: 'day'}
1: {path: 'image', location: 'LOCATION_2', time: 'week'}
2: {path: 'image', location: 'LOCATION_1', time: 'year'}
3: {path: 'image', location: 'LOCATION_1', time: 'week'}
4: {path: 'image', location: 'LOCATION_1', time: 'month'}
5: {path: 'image', location: 'LOCATION_2', time: 'day'}
6: {path: 'image', location: 'LOCATION_2', time: 'month'}
7: {path: 'image', location: 'LOCATION_2', time: 'year'}
]
I want to sort them based on time but when I do, it goes like
day
month
week
year
Is there any way to make it like:
day
week
month
year
I am using functional component in javascript.
Solution 1:[1]
use the sort method like this
mdn : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
let arr =
[
{path: 'image', location: 'LOCATION_1', time: 'day'},
{path: 'image', location: 'LOCATION_2', time: 'week'},
{path: 'image', location: 'LOCATION_1', time: 'year'},
{path: 'image', location: 'LOCATION_1', time: 'week'},
{path: 'image', location: 'LOCATION_1', time: 'month'},
{path: 'image', location: 'LOCATION_2', time: 'day'},
{path: 'image', location: 'LOCATION_2', time: 'month'},
{path: 'image', location: 'LOCATION_2', time: 'year'}
];
let sortBy = ["day", "week", "month", "year"]
console.log(arr.sort((a,b) => sortBy.indexOf(a.time) - sortBy.indexOf(b.time)))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
