I'm trying to sort an object but it's not working.
Suppose I have three objects in an array:
let arr = [
{
id: 1,
tipos: [{id_vista: 10, nombre: "emprendimiento", orden: 2}]
},
{
id: 3,
tipos: [{id_vista: 10, nombre: "emprendimiento", orden: 3}, {id_vista: 12, nombre: "edificio",
orden: 1}]
},
{
id:2,
tipos: [{id_vista: 8, nombre: "desarrollo", orden: 10}, {id_vista: 10, nombre: "emprendimiento",
orden: 1}]
}
]
Now, as you will see, I have the "Types" array, which is a property. The type tells me that this object will be listed in one or more views, for example:
The one with id 1 will be listed in Entrepreneurship
The one with id 2 will be listed in Developments and Entrepreneurship
The one with id 3 will be listed in Undertakings and Buildings
Let's suppose that I am in the start-ups view, and I want to order the array arr
according to the property orden
that is found in the object that is in the array tipos
, which has id_vista
10 (corresponding to start-ups). I should keep (according to your ids
) 2, then 1 and finally 3.
This is what I'm trying but it doesn't work for me:
let arr = [
{
id: 1,
tipos: [{id: 10, nombre: "emprendimiento", orden: 2}]
},
{
id: 3,
tipos: [{id: 10, nombre: "emprendimiento", orden: 3}, {id: 12, nombre: "edificio",
orden: 1}]
},
{
id:2,
tipos: [{id: 8, nombre: "desarrollo", orden: 10}, {id: 10, nombre: "emprendimiento",
orden: 1}]
}
]
arr.sort((a,b) => {
b.tipos.map(e =>
{
if(e.id == 10){
a.tipos.map(f => {
if(f.id == 10){
return e.orden - f.orden
}
})
}
})
})
console.log(arr)
I am getting the same array without sorting.
In the function that you pass to sort, you must first find the element corresponding to the view you are in, and then find the order of that element. With that, the array will be ordered as you want.
One important thing is that this method will fail if the element doesn't have the required view, since there is no way for sort to know what to compare to.