Ad

How To Reorder All Array Items To Specific Index In React?

- 1 answer

My users are able to reorder a list of categories and I need to persist indexes of the array items so the order stays even when the user closes the app.

I have tried this, but it does not work because the data changes when mapping. I just can't get the logic in my head, how to achieve this.

Below is example data, and the logic I've attempted:

order: [
  {id: "5", index: 0},
  {id: "4", index: 1},
  {id: "1", index: 2},
  {id: "2", index: 3},
  {id: "3", index: 4},
]

data: [
  {id: "1", category: "Category1"},
  {id: "2", category: "Category2"},
  {id: "3", category: "Category3"},
  {id: "4", category: "Category4"},
  {id: "5", category: "Category5"},
]

orderCategories = (data, order) => {
  data.map((dataValue, dataIndex) => {
    order.map((value, index) => {
      if (dataValue.id === value.id && dataIndex !== index) {
        this.setState({data: arrayMove(data, dataIndex, index)})
      }
    });
  });
};

Below is the resulting data array:

data: [
  {id: "5", category: "Category5"},
  {id: "1", category: "Category1"},
  {id: "2", category: "Category2"},
  {id: "3", category: "Category3"},
  {id: "4", category: "Category4"},
]

But I want it to be:

data: [
  {id: "5", category: "Category5"},
  {id: "4", category: "Category4"},
  {id: "1", category: "Category1"},
  {id: "2", category: "Category2"},
  {id: "3", category: "Category3"},
]

What am I doing wrong here?

Ad

Answer

You can do something like this:

orderCategories = (data, order) => {
order.forEach(order => {
    result[order.index] = data.find(data => data.id === order.id)
  }
return result;
)}
Ad
source: stackoverflow.com
Ad