react sort state array code example
Example 1: sort array of objects in react js
const list = [
{ color: 'white', size: 'XXL' },
{ color: 'red', size: 'XL' },
{ color: 'black', size: 'M' }
]
list.sort((a, b) => (a.color > b.color) ? 1 : -1)
Example 2: sort by attribute in reactjs
const list = [
{ qty: 10, size: 'XXL' },
{ qty: 2, size: 'XL' },
{ qty: 8, size: 'M' }
]
list.sort((a, b) => (a.qty - b.qty) ? 1 : -1)
console.log(list)