Skip to content

Instantly share code, notes, and snippets.

@crazy4groovy crazy4groovy/sort-by.js
Last active Nov 11, 2019

Embed
What would you like to do?
custom array sort, by field path and weighted values
function getVal(obj, fields) {
if (!(obj && fields[0])) return obj
return getVal(obj[fields.shift()], fields)
}
export const customSort = (field, byVals) => {
let sorter
if (byVals) {
const sortByWeight = {}
byVals.forEach((val, weight) => {
sortByWeight[val] = weight
})
sorter = (a, b) => sortByWeight[a] - sortByWeight[b]
} else {
sorter = (a, b) => a > b ? 1 : -1
}
return (arr) => arr.sort((a, b) => sorter(
getVal(a, field.split('.')),
getVal(b, field.split('.'))
))
}
///////
const arr = [
{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(sortField)(arr)) // natural sort order
let sortByVals = ['inProgress', 'todo', 'done']
console.log(customSort(sortField, sortByVals)(arr)) // weighted sort order
sortField = 'tags.flower' // dot path
console.log(customSort(sortField)(arr)) // natural sort order
sortByVals = [true, false]
console.log(customSort(sortField, sortByVals)(arr)) // weighted sort order
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.