Yunyi Chang
Yunyi Chang

Reputation: 169

sort object base on array to produce sorted array

Object doesn't guantee order when I display it so I have to convert an existing object into array, but follow the order.

I have this array as the order [1,2,3]

and this is my raw input aka source

{'2': 'two',
'3': 'three',
'1':'one'}

How can I make a function to produce a new array where the order follow the sorted key above?

I'm stuck at this stage

//expected 
['one', 'two', 'three']
const order = ['1', '2', '3']
const source = {
  '2': 'two',
  '3': 'three',
  '1': 'one'
}

let sorted = Object.keys(source).map(o => {
  //return order.includes(o) ? //what to do here : null
})

I think I have to do loop within loop.

Upvotes: 3

Views: 67

Answers (2)

charlietfl
charlietfl

Reputation: 171690

Can simply map order array and return the corresponding value from source. Anything beyond that is over complicating it

const order = ['1', '2', '3']
const source = {
  '2': 'two',
  '3': 'three',
  '1': 'one'
}

const sorted = order.map(n=>source[n])

console.log(sorted)

Upvotes: 3

31piy
31piy

Reputation: 23859

You can reduce the ordering array, and find the relevant strings from the source object. This method uses only one loop, and thus, is more efficient.

const order = ['1', '2', '3', '4', '5'];
const source = {
  '2': 'two',
  '5': 'five',
  '3': 'three',
  '1': 'one',
  '4': 'four'
};

let sorted = order.reduce((obj, item) => {
  obj.push(source[item]);
  return obj;
}, []);

console.log(sorted);

Upvotes: 0

Related Questions