1

I need to reorder some objects in an array.

Assume this is my data array:

const data = [
  { id: 'ETHUVMY0m', name: 'item 1', value: 'value 1' },
  { id: 'McfTB40vO', name: 'item 2', value: 'value 2' }
]

And there is another array, which represents the new order:

const order = [ 'McfTB40vO', 'ETHUVMY0m' ]

As you can see, the second item gets on the first place.

So the result should be:

[
  { id: 'McfTB40vO', name: 'item 2', value: 'value 2' },
  { id: 'ETHUVMY0m', name: 'item 1', value: 'value 1' }
]

I thought of using an forEach loop:

data.forEach(d => {
  order.indexOf(d.id) // get new index
  // but how to reorder the array?
})
1
  • 2
    you would build your own custom sort and pass the custom function to sort Commented Mar 18, 2019 at 21:17

3 Answers 3

3

Convert the data to a Map of objects by id. Then use Array.map() on the order array, and get the relevant item from the Map:

const data = [
  { id: 'ETHUVMY0m', name: 'item 1', value: 'value 1' },
  { id: 'McfTB40vO', name: 'item 2', value: 'value 2' }
]

const order = [ 'McfTB40vO', 'ETHUVMY0m' ]

const dataMap = new Map(data.map(o => [o.id, o]))
const result = order.map(id => dataMap.get(id))

console.log(result)

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

Comments

2

If you want to do it immutably, use map and find, not forEach:

const data = [
  { id: 'ETHUVMY0m', name: 'item 1', value: 'value 1' },
  { id: 'McfTB40vO', name: 'item 2', value: 'value 2' }
];

const order = [ 'McfTB40vO', 'ETHUVMY0m' ];

const result = order.map(id => data.find(x => x.id === id));

console.log(result);

3 Comments

If you reduce() order into a Map before using Array.prototype.map(), you can perform this in O(n) using Map.prototype.has() instead of Array.prototype.find().
@PatrickRoberts I don't understand what you suggest. Could you give an example?
@user3142695, look at Ori Drori's answer for a solution using Map.get(), which is more efficient than using find()
0

You could map over order:

const data = [{
    id: 'ETHUVMY0m',
    name: 'item 1',
    value: 'value 1'
  },
  {
    id: 'McfTB40vO',
    name: 'item 2',
    value: 'value 2'
  }
]

const order = ['McfTB40vO', 'ETHUVMY0m']

const output = order.map(d => data.find(({
  id
}) => d == id));

console.log(output);

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.