0

I am receiving an array of objects from a server but they are not in the order I want to spit them back out. Unfortunately, the order I want is not alphabetical either. I am wondering what the best way to re-order the array elements is. Also, if there is a way I can leverage array.sort. How I have it working now:

function arraySort(array) {
  let orderedArray = new Array();
  array.map(item => (
    item.key === 'Person' ? orderedArray[0] = item : null,
    item.key === 'Place' ? orderedArray[1] = item : null,
    item.key === 'Thing' ? orderedArray[2] = item : null
  ));
  return orderedArray;
}
Jlegend
  • 531
  • 1
  • 6
  • 19
  • 2
    Did you know that you can pass a custom comparison function to [`sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)? – Mike Cluck Aug 11 '16 at 21:02
  • 6
    Possible duplicate of [How to define custom sort function in javascript?](http://stackoverflow.com/questions/5002848/how-to-define-custom-sort-function-in-javascript) – Danny Buonocore Aug 11 '16 at 21:02
  • I don't think this is a duplicate. OP is asking how to implement an arbitrary sort – Mulan Aug 11 '16 at 21:03
  • 1
    @JLegendre, are there multiple `Person`, `Place`, or `Thing` results in the input array? Can you also paste a sample input and expected output? – Mulan Aug 11 '16 at 21:05
  • For a longer array you might want to first group the items by key, and then iterate over the `order`-array and concat the groups (in the right order) – Thomas Aug 11 '16 at 22:21

1 Answers1

2

Here you go.

var order = ['Person', 'Place', 'Thing'];
var a = [
  { key: 'Place' },
  { key: 'Thing' },  
  { key: 'Place' },  
  { key: 'Person' },
  { key: 'Place' },
  { key: 'Thing' },
  { key: 'Person' }  
];

var b = a.sort(function(a,b) {
  return order.indexOf(a.key) - order.indexOf(b.key);
});

console.log(b);
Sebastian Sebald
  • 16,130
  • 5
  • 62
  • 66