0

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?

3 Answers 3

1

You can do something like this:

orderCategories = (data, order) => {
order.forEach(order => {
    result[order.index] = data.find(data => data.id === order.id)
  }
return result;
)}
Sign up to request clarification or add additional context in comments.

Comments

0

It may be easier to store the index in the same data object so that you can use .sort

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

then sort like this:

data.sort((a, b) => a.index - b.index)



Comments

0

You can use .sort() funnction and pass comparer as a parameter.

orderCategories = (data, order) => {
  return data.sort((item1, item2) => {
     const index1 = order.find(orderItem => orderItem.id === item1.id).index;
     const index2 = order.find(orderItem => orderItem.id === item2.id).index;

    return index1 - index2;
  });
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.