Skip to content

Instantly share code, notes, and snippets.

@crazy4groovy
Last active April 1, 2021 14:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crazy4groovy/b1450e064875958b3859d046c88ef197 to your computer and use it in GitHub Desktop.
Save crazy4groovy/b1450e064875958b3859d046c88ef197 to your computer and use it in GitHub Desktop.
custom array sort, by field path and weighted values (JavaScript)
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