Move object up and down within array

Viewed 17995

I have a table of data that is rendered from an object. Specifically, each row of the table is a value from the array.

I need to be able to move the object up or down in the array, depending on the button clicked.

var obj = [{
  "RuleDetailID": "11624",
  "AttributeValue": "172",
  "Value": "Account Manager",
  "IsValueRetired": "0"
}, {
  "RuleDetailID": "11626",
  "AttributeValue": "686",
  "Value": "Agent",
  "IsValueRetired": "0"
}, {
  "RuleDetailID": "11625",
  "AttributeValue": "180",
  "Value": "Analyst",
  "IsValueRetired": "0"
}, {
  "RuleDetailID": "11629",
  "AttributeValue": "807",
  "Value": "Individual Contributor",
  "IsValueRetired": "0"
}, {
  "RuleDetailID": "11627",
  "AttributeValue": "690",
  "Value": "Senior Agent",
  "IsValueRetired": "0"
}];

// Exmaple only, just rendering a table
function renderExample() {
  var table = '';
  for (var key in obj) {
    table += "<tr><td>" + obj[key].Value + "</td><td><a href=\"#\" onClick=\"move('up', " + obj[key].RuleDetailID + ")\">Move Up</a></td><td></td><td><a href=\"#\" onClick=\"move('down', " + obj[key].RuleDetailID + ")\">Move Down</a></td></tr>";
  }
  return table;
}

// Move the object in the array up or down
function move(value, positionChange) {

  // On run, move the object in the array up or down respectivly.

}
<table>
  <tbody id="example">
    <script>
      document.write(renderExample())
    </script>
  </tbody>
</table>

Can this be done with something like lodash or is it more of a manual approach? I tried by getting the index of the clicked item and then doing +1 or -1 accordingly to give me the new index. However, I wasn't sure what to do at that point since another item would already exist at that index.

How can I go about achieving this? Not looking for a jQuery approach, javascript or a library such as lodash only.

2 Answers

You can use array.splice twice, first to remove the item you want to move, and then to insert it into the new position

var data = [1,2,3,4,5];

function moveItem(from, to) {
  // remove `from` item and store it
  var f = data.splice(from, 1)[0];
  // insert stored item into position `to`
  data.splice(to, 0, f);
}

moveItem(0, 2);

console.log(data);

You can also use an old-school swap mechanism:

function move(value, positionChange) {
  // On run, move the object in the array up or down respectivly.
  for (var i = 0; i < obj.length; i++) {
    if (obj[i].RuleDetailID == positionChange) {
      var newIndex = value === 'up' ? i - 1 : i + 1;
      if (newIndex >= obj.length || newIndex < 0) return;
      var temp = obj[i];
      obj[i] = obj[newIndex];
      obj[newIndex] = temp;
      document.getElementById('example').innerHTML = renderExample();
    }
  }
}
Related