Answers for "sort array of objects based on array of objects fields"

2

sort array with objects

const list = [
  { color: 'white', size: 'XXL' },
  { color: 'red', size: 'XL' },
  { color: 'black', size: 'M' }
]

var sortedArray = list.sort((a, b) => (a.color > b.color) ? 1 : -1)

// Result:
//sortedArray:
//{ color: 'black', size: 'M' }
//{ color: 'red', size: 'XL' }
//{ color: 'white', size: 'XXL' }
Posted by: Guest on June-06-2021
0

javascript sort array of objects multiple fields

array.sort(function(a,b){
  let i = 0, result = 0;
  while(i < sortBy.length && result === 0) {
    result = sortBy[i].direction*(a[ sortBy[i].prop ].toString() < b[ sortBy[i].prop ].toString() ? -1 : (a[ sortBy[i].prop ].toString() > b[ sortBy[i].prop ].toString() ? 1 : 0));
    i++;
  }
  return result;
})
Posted by: Guest on March-02-2021

Code answers related to "sort array of objects based on array of objects fields"

Code answers related to "Javascript"

Browse Popular Code Answers by Language