Jlegend
Jlegend

Reputation: 563

Best way to put array elements in custom order in Javascript

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

Upvotes: 0

Views: 89

Answers (1)

Sebastian Sebald
Sebastian Sebald

Reputation: 16876

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

Upvotes: 2

Related Questions