Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!