Sort an array of objects taking into account the order of the values of another array

-4

The problem is this:

I have a array of objects, which have properties id and orden (both integers). This array I must order it taking into account the property orden , depending on the order of the values that are in another array of integers.

For example, if I have the following% co_of% of objects:

objs = [
    { order: 1, id: 121 },
    { order: 2, id: 122 },
    { order: 3, id: 123 },
    { order: 4, id: 124 },
    { order: 5, id: 125 },
]

And a array with the values of the desired order:

orden = [5, 3, 2, 4, 1]

The result of ordering the first array should be:

objs = [
    { order: 5, id: 125 },
    { order: 3, id: 123 },
    { order: 2, id: 122 },
    { order: 4, id: 124 },
    { order: 1, id: 121 },
]

This is the code to show the elements of array array :

orden.forEach((el, i) => {
    console.log(el);
});
    
asked by Piero Pajares 12.04.2018 в 17:44
source

1 answer

2

What you must do first is to go through the array where you have your order established. And then go find within your arrangement objs the item that has this order.

Now, what the code does is that we make a map on the array order (remember that the map function creates a new array with the mapped results).

Then, since we have an order in each iteration, we must go to find the object with this order within your objs array and for this we use the function find . The find function returns the first element that meets the condition:

let items = orden.map(orden => {
  return objs.find(x => x.order === orden)
})

I leave you here a little so you can read more about map and find: link link

Greetings.

    
answered by 12.04.2018 в 17:57