Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading