Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

45
Vistas
How to sort by order in another array?

I have the first array that be like

status = [
{title: 'pending', order: 1},
{title: 'success', order: 2}
]

And I have the second array that be like

task = [
{status: 'success', price: 100},
{status: 'success', price: 150},
{status: 'pending', price: 100}, 
{status: 'success', price: 300}
]

How Can I sort This for results be like

task = [
{status: 'pending', price: 100},
{status: 'success', price: 100},
{status: 'success', price: 150},
{status: 'success', price: 300}
]

sort by order of status from the first array

7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can easily achieve the result using Map and by passing the comparator function to sort method

const status = [
  { title: "pending", order: 1 },
  { title: "success", order: 2 },
];

const task = [
  { status: "success", price: 100 },
  { status: "success", price: 150 },
  { status: "pending", price: 100 },
  { status: "success", price: 300 },
];

const dict = new Map(status.map(o => [o.title, o.order]));
const result = [...task].sort((a, b) => dict.get(a.status) - dict.get(b.status));

console.log(result);
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos