Sorting array of objects in Redux reducer
The sorting function should work fine. But you should not mutate the original state in the reducer. You can create a copy of the state
array by calling state.slice()
before sorting.
case 'SORT_COLLECTION':
return state.slice().sort(function(a, b) {
var nameA = a.name.toLowerCase(),
nameB = b.name.toLowerCase()
if (nameA < nameB)
return -1
if (nameA > nameB)
return 1
return 0
})
Of course, you can define a simpler sort function as well.
const state = [{name:'foo'},{name:'bar'},{name:'baz'}]
const sortByKey = key => (a, b) => a[key] > b[key] ? 1 : -1
const sorted = state.slice().sort(sortByKey('name'))
console.log(`state=${JSON.stringify(state)}\nsorted=${JSON.stringify(sorted)}`)