Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

182
Vistas
Sort an array based on another array

I have a list of questions that I'd like to render as sortable cards. The data looks something like this:

const questionList = [
  {
    id: 1,
    data: {
      question: "What is your name?"
    }
  },
  {
    id: 2,
    data: {
      question: "How old are you?"
    }
  }
...
]

I'm using Framer Motion to extract the ids and render a Reorder.Group component which works fine for drag to reorder:

<Reorder.Group values={listIds} onReorder={handleReorder}>
        {listIds.map((id) => {
          return (
            <Reorder.Item className="card" key={id} value={id}>
              <span>{id}.</span>
              <span>{questions[id - 1].data.question}</span>
            </Reorder.Item>
          );
        })}
</Reorder.Group>

The full implementation can be found here - https://codesandbox.io/s/nice-stitch-48v0ee

I'd like to however persist the new question order which means I need to re-arrange the items in the questionList to match whatever new order. How can I match the array of questions (with ids) to always match new indexes generated by re-ordering? So, if the user changes the initial order to [2, 1, 3, 4, 5] I want to sort the questionList so that the question ids match this new order.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can do it using the map function on the second array where you find the element matching the number

Example

const questions = [
  {
    id: 1,
    data: {
      question: "What is your name?"
    }
  },
  {
    id: 2,
    data: {
      question: "How old are you?"
    }
  },
  {
    id: 3,
    data: {
      question: "Where do you leave?"
    }
  },
  {
    id: 4,
    data: {
      question: "Foo"
    }
  },
  {
    id: 5,
    data: {
      question: "Bar"
    }
  },
]

const newOrder = [2,1,5,4,3]

const newQuestionsOrdered = newOrder.map(x => questions.find(question => question.id === x))

console.log(newQuestionsOrdered)

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda