0

I have 5 li elements, while I click on each of them, I am adding a class name on and push it into an array. I would like to remove the item from the object when a user is clicking again.

<ul>
  <li class="on" data-index="3">add 3</li>
  <li data-index="4">add 4</li>
  <li data-index="5">add 5</li>
  <li class="on" data-index="6">add 6</li>
</ul>

When a user clicks on a li I add a class called on and push the value into an array and sort the array after I pushed the item.

If a user clicks again on the li I can't remove the value from the array, because of the sort. Is there a way I can achieve this?

I don't have any idea to do the functionality regarding this.. any one can help me? I tried with splice, but no result.

Wouter J
  • 39,482
  • 15
  • 97
  • 108
3gwebtrain
  • 13,401
  • 21
  • 93
  • 195

1 Answers1

1

You can use delete arr[index] syntax to remove any element from array. Try this:

var arr = {};
$('ul > li').click(function () {
   $(this).toggleClass('on');
    if ($(this).hasClass('on')) {
       arr[$(this).attr('data-index')] = $(this).html();
    } else {
        delete arr[$(this).attr('data-index')];
    }
    console.log(sortObj(arr));
});

function sortObj(arr){
    var sortedKeys = new Array();
    var sortedObj = {};

    for (var i in arr){
        sortedKeys.push(i);
    }
    sortedKeys.sort();

    for (var i in sortedKeys){
        sortedObj[sortedKeys[i]] = arr[sortedKeys[i]];
    }
    return sortedObj;
}

Demo : http://jsfiddle.net/codef0rmer/AEYtq/1/

codef0rmer
  • 9,854
  • 9
  • 46
  • 75