Home > Blockchain >  Sort an array based on another array
Sort an array based on another array

Time:05-04

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.

CodePudding user response:

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)

  • Related