Skip to content

Instantly share code, notes, and snippets.

@crazy4groovy crazy4groovy/sort-by.js
Last active Aug 13, 2019

Embed
What would you like to do?
export const customSort = ({data, sortField, sortBy}) => {
let sortVal
if (sortBy) {
const sortByWeight = sortBy.reduce(
(obj, item, index) => ({
...obj,
[item]: index
}), {})
sortVals = (val1, val2) => sortByWeight[val1] - sortByWeight[val2]
} else {
sortVals = (val1, val2) => val1 > val2 ? 1 : -1
}
const sortFields = sortField.split('.')
const getVal = (obj, fields) => {
if (!(obj && fields[0])) return obj
return getVal(obj[fields.shift()], fields)
}
return data.sort((a, b) => sortVals(
getVal(a, sortFields.slice(0)),
getVal(b, sortFields.slice(0))
))
}
const data = [
{id:1, title: 'Job A', status: 'done', tags: { flower: true }},
{id:2, title: 'Job B', status: 'inProgress', tags: { flower: false }},
{id:3, title: 'Job C', status: 'todo', tags: { flower: true }},
{id:4, title: 'Job D', status: 'inProgress', tags: { flower: false }},
{id:5, title: 'Job E', status: 'todo', tags: { flower: false }}
]
let sortField = 'status'
console.log(customSort({data, sortField}))
let sortBy = ['inProgress', 'todo', 'done']
console.log(customSort({data, sortField, sortBy}))
sortField = 'tags.flower'
console.log(customSort({data, sortField}))
sortBy = [true, false]
console.log(customSort({data, sortField, sortBy}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.