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;
}
5
  • 2
    Did you know that you can pass a custom comparison function to sort? Commented Aug 11, 2016 at 21:02
  • 6
    Possible duplicate of How to define custom sort function in javascript? Commented Aug 11, 2016 at 21:02
  • I don't think this is a duplicate. OP is asking how to implement an arbitrary sort Commented Aug 11, 2016 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? Commented Aug 11, 2016 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) Commented Aug 11, 2016 at 22:21

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

3 Comments

Nice work. This is probably the best answer you can give without knowing more from the OP.
Thank you! This is exactly what I was looking for!
@JLegendre next time post a sample input and expected output with your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.