0

This is not a duplicate because I want to select the order based on the chosen category by the user.

Trying to sort an array of objects by category array field i.e sort by user selected category from maybe a selected list.

Any help would be much appreciated.

var users = [
  { 'user': 'barne1y', 'age': 34, 'category':['a','b','c','d','e']},
  { 'user': 'fred',   'age': 40, 'category':['a','b','c','d']},
  { 'user': 'fred',   'age': 48, 'category':['a','b'] },
  { 'user': 'barney', 'age': 36, 'category':['a','b','c']}
];

example: I have a list of users that can be appear in multiple categories as shown in the json data above then in the UI I have a selected list with all the possible categories e.g.

<select><option>a</option><option>b</option><option>c</option><option>d</option></select>

When an option e.g a is selected the data is then sorted using that value found in the category.

kdev
  • 1
  • 1

2 Answers2

0

You can sort this collection by using Array.prototype.sort() and passing in a compare function:

var users = [
  { 'user': 'barne1y', 'age': 34, 'category':['a,b,c,d,e']},
  { 'user': 'fred',   'age': 40, 'category':['a,b,c,d']},
  { 'user': 'fred',   'age': 48, 'category':['a,b'] },
  { 'user': 'barney', 'age': 36, 'category':['a,b,c']}
]; 

var sortedUsers = users.sort(sortByAge);

function sortByAge(a, b) {
  return a.age - b.age;
}
hackerrdave
  • 6,486
  • 1
  • 25
  • 29
0

var users = [
  { 'user': 'barne1y', 'age': 34, 'category':['a','b','c','d','e']},
  { 'user': 'fred',   'age': 40, 'category':['a','b','c','d']},
  { 'user': 'fred',   'age': 48, 'category':['a','b'] },
  { 'user': 'barney', 'age': 36, 'category':['a','b','c']}
];

users.sort(function(a, b) {
  return a.category.length - b.category.length; // reverse the order if you want descending sort
});

console.log(users);
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
  • thanks @ibrahim mahrir for your solution but the problem I had was that I wanted to want to sort via a value selected from a dropdown list. – kdev Feb 07 '17 at 01:52
  • @kdev check the link for the duplicate. It has what you need! – ibrahim mahrir Feb 07 '17 at 02:11
  • its not a duplicate since want to sort by category value coming from the user – kdev Feb 07 '17 at 12:31
  • @kdev Post some example. The question still a little bit foggy! – ibrahim mahrir Feb 07 '17 at 12:37
  • @kdev do you mean `filter`? (**i.e** show only the users that have that category)? – ibrahim mahrir Feb 07 '17 at 13:44
  • nope, imagine a list of posts, some belong to multiple categories but you now need to order them by a category called 'books'... some posts may belong to 'books' only and some belong to both magazines and books. How would you go about ordering them? – kdev Feb 07 '17 at 16:21