0

Let's say I have an array like this:

var objects = [
  { name: "steve", status: added },
  { name: "john", status: added },
  { name: "drew", status: none },
  { name: "aaron", status: none },
  { name: "jeff", status: hidden },
  { name: "gil", status: hidden },
  { name: "marc", status: removed },
  { name: "bill", status: removed }
];

...and I would like to sort it by status but have:

  • the "removed" ones first,
  • the "added" ones second,
  • the "none" ones third, and
  • the "hidden" ones last.

Seeing as how that is not alphabetical how would I go about doing this using the sort method?

The only idea I could think of is to make each object with their respective statuses an array then concat them back together. Thank you.

user1039663
  • 1,230
  • 1
  • 9
  • 15
jb_castro
  • 11
  • 4

2 Answers2

0

You should implement a sort compareFunction, given your array variable named objects:

objects = [
  { name: "steve", status: added },
  ...
]

You should use:

objects.sort(compareFunction);

Where objects is your array instance and compareFunction is a function that you can define with your criteria.

In the compare function return 1, 0 or -1 depending on your sort criteria.

For example, you can use an auxiliar associative object:

var aux = {
  "removed": 1, "added": 2, "none": 3, "hidden": 4
};

Then your compare function will be:

objects.sort(function(a,b) {
  return aux[a.status] - aux[b.status];
});
user1039663
  • 1,230
  • 1
  • 9
  • 15
0

Assign a value to each of the statuses based on the order you'd like them to display, and then compare the mapped ordered values.

const arr = [
  { name: "steve", status: "added" },
  { name: "john", status: "added" },
  { name: "drew", status: "none" },
  { name: "aaron", status: "none" },
  { name: "jeff", status: "hidden" },
  { name: "gil", status: "hidden" },
  { name: "marc", status: "removed" },
  { name: "bill", status: "removed" }
];

const order = {
  removed: 1,
  added: 2,
  none: 3,
  hidden: 4,
};

arr.sort((a, b) => order[a.status] - order[b.status]);

// ordered: removed, added, none, hidden
console.log(arr);
fubar
  • 16,918
  • 4
  • 37
  • 43