• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

131
Views
Reordenar una matriz de objetos en función de los datos de otra matriz en Javascript (React)

Me encargaron tomar una serie de objetos que representan a 'consultores' con identificaciones para cada uno y reorganizarlos en función de los consultores seleccionados más recientes de una reserva de sesión.

Así que tengo una serie de objetos de las próximas sesiones con el más reciente al último:

ingrese la descripción de la imagen aquí

Y tengo una matriz de objetos de todos los consultores:

ingrese la descripción de la imagen aquí

Por lo tanto, therapistId de 'próximas sesiones' id de coincidencia de 'consultores'

Escribí un método que extrae a los terapeutas de las 'próximas sesiones' en una nueva matriz y luego concatena el resto, manteniendo el orden de los terapeutas de las 'próximas sesiones'.

Entonces, el usuario verá los terapeutas seleccionados más recientemente en un menú desplegable.

El método que escribí funciona pero tiene un bucle forEach() anidado porque filter() solo seleccionó a los consultores usados pero no mantiene el orden.

Aquí está el método:

 const handleUpdatedConsultantList = () => { // first capture the ids of chosen therapists const consultantIds = upcomingSessions.map((us) => us.therapistId) // create an array of remaining therapists const remainingConsultants = consultants.filter( (c) => !consultantIds.includes(c.id), ) // empty array to push in the entire object of each chosen therapist const recentConsultants: ConsultantType[] = [] // method to push in therapists by most recent consultantIds.forEach((c) => { consultants.forEach((co) => { if (c === co.id) { recentConsultants.push(co) } }) }) // concat most recent with remaining return recentConsultants.concat(remainingConsultants) }

Mi pregunta es, ¿es esta la mejor manera de implementar esto? Los bucles anidados siempre me hacen sentir incómodo, pero ¿tal vez sea la única forma de mantener el orden de los consultores seleccionados?

Esto obtiene los consultores elegidos filtrados pero ordena las identificaciones de menor a mayor en lugar del orden que se seleccionó:

 const selectedConsultants = consultants.filter((c) => [313, 312, 311, 302].includes(c.id))
about 3 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Creo que puede obtener más directamente su lista de recentConsultants utilizando una búsqueda find() al mapear los consultantIds .

 const handleUpdatedConsultantList = () => { // first capture the ids of chosen therapists const recentConsultantIds = upcomingSessions.map((us) => us.therapistId); // map through ids and connect with consultant profiles const recentConsultants = recentConsultantIds.map((id) => consultants.find((c) => c.id === id) ); // create an array of remaining therapists const remainingConsultants = consultants.filter( (c) => !recentConsultantIds.includes(c.id) ); // concat most recent with remaining return recentConsultants.concat(remainingConsultants); };
about 3 years ago · Juan Pablo Isaza Report

0

Un mapa hará el trabajo bien:

 const upcomingSessions = [ {therapistId: 5}, {therapistId: 8}, {therapistId: 9}, {therapistId: 7} ]; const consultants = [ {id: 1}, {id: 2}, {id: 3}, {id: 5}, {id: 6}, {id: 7}, {id: 8}, {id: 9}, {id: 10}, {id: 11}, {id: 12} ]; const recentConsultants = new Map(upcomingSessions.map(us => [us.therapistId, ])); consultants.forEach(c => recentConsultants.set(c.id, c)); console.log([...recentConsultants.values()]);

about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error