How add and remove array without re-index array key in JQuery

Viewed 1330

I have a list of the checkbox when clicking on any checkbox than new array append (push) in the main array. If uncheck than remove but not change any index for the current array.

explain:-

Like:- When I click on the first checkbox than array like

0: ["2"]

Like:- When I click on the second checkbox than array like

0: ["2"]
1: ["3"]

Like :- When I click on four checkbox than array like

0: ["2"]
1: ["3"]
2: ["5"]

after than uncheck checkbox if I uncheck first tthe han I needed array

1: ["3"]
2: ["5"]

again I click on first checkbox than need array link

1: ["3"]
2: ["5"]
3: ["2"]

Not need to change any array index key

https://jsfiddle.net/tx63yjhg/

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" />
<input type="checkbox" value="2" />
<input type="checkbox" value="3" />
<input type="checkbox" value="4" />
<input type="checkbox" value="5" />
<input type="checkbox" value="6" />
<input type="checkbox" value="7" />

<script type="text/javascript">
var values = [];
var new_value = [];

$("input").on("change", function() 
{
  var $this = $(this);
  
  if ($this.is(":checked")) 
  {
   var new_data = [$this.val()];
   new_value.push(new_data);
  }
  else 
  { 
   //remove array when uncheck checkbox
  }
  console.log('new_value',new_value);
});
</script>

How I can remove array and add again??

2 Answers

I am not sure whether you achieve the same using an array of arrays or not. You can instead try use an object like following.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" />
<input type="checkbox" value="2" />
<input type="checkbox" value="3" />
<input type="checkbox" value="4" />
<input type="checkbox" value="5" />
<input type="checkbox" value="6" />
<input type="checkbox" value="7" />

<script type="text/javascript">
var values = [];
var new_value = {};
var counter = 0;

$("input").on("change", function() {
  var $this = $(this);
  
  if ($this.is(":checked")) {
    new_value[counter++] = [$this.val()];
  } else { 
    Object.entries(new_value).forEach(([k,v]) => {
      if(v.includes($this.val())) delete new_value[k];
    });
  }
  console.log('new_value',new_value);
});
</script>

EDIT

For add

new_value[counter++] = {id1: 100, id2: 200, "id3": 300,"value":474}; // e.g. object

For remove

let valueToBeRemoved = 234; // e.g. value to be removed

Object.entries(new_value).forEach(([k,v]) => {
  if(v.value === valueToBeRemoved) delete new_value[k];
})

EDIT 2

for (var k in new_value) {
    if(new_value[k].value === valueToBeRemoved) delete new_value[k];
}

It easy:

var values = [];

$("input").on("change", function() 
{
  var $this = $(this);
  var new_value = [];
  
  if ($this.is(":checked")) 
  {
   var new_data = [$this.val()];
   new_value.push(new_data);
  }
  console.log('new_value',new_value);
});

Related