3

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.

1
  • I find it funny how you post a problem that should in all normal cases not be solved by using property order, realize that, and then use about the only example possible where relying on property order would work. Commented Jul 2, 2018 at 2:51

2 Answers 2

3

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)

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

Comments

0

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

Comments

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.