0

I have an object array That is in this format

sampleItemDetail: [
    {
      type: 'Take out the garbage',
      isBox1: true
    },
    {
      type: 'Watch my favorite show',
      isBox1: true
    },
    {
      type: 'Charge my phone',
      isBox2: true
    },
    {
      type: 'Cook dinner',
      isBox1: true
    },
    {
      type: 'Take out the garbage1',
      isBox2: true
    },
    {
      type: 'Watch my favorite show2',
      isBox1: true
    },
    {
      type: 'Charge my phone3',
      isBox1: true
    }
]

I am using react-beautiful-dnd to drag and drop this array of objects. I want to be able to assign the index based on drag and drop as well as the isBox flag too. What will be the most efficient way of doing this. I am confused since the state does not have index. Would I need to add an index property to the elements to make that happen?

https://codesandbox.io/s/react-beautiful-dnd-tutorial-forked-ij1oq?file=/src/index.js

Kimaya
  • 1,210
  • 4
  • 14
  • 33

1 Answers1

0

You can try this assuming the size of the items array is always 3:

// Create a local shallow copy of the state
var items = this.state.items.slice()

// Find the index of the selected item within the current items array.
var selectedItemName = this.state.selected;
function isSelectedItem(element, index, array) {
    return element.id === selectedItemName;
};
var selectedIdx = items.findIndex(isSelectedItem);

// Extract that item
var selectedItem = items[selectedIdx];

// Delete the item from the items array
items.splice(selectedIdx, 1);

// Sort the items that are left over
items.sort(function(a, b) {
    return a.id < b.id ? -1 : 1;
});

// Insert the selected item back into the array
items.splice(1, 0, selectedItem);

// Set the state to the new array
this.setState({items: items});
Taoufik
  • 482
  • 5
  • 13
  • I was able to get it to almost work but keep losing items for some reason https://codesandbox.io/s/react-beautiful-dnd-tutorial-forked-ij1oq?file=/src/index.js –  Kimaya Aug 26 '20 at 16:28