Ad
How To Reorder All Array Items To Specific Index In React?
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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad