0

I am working on a function that involves a checkbox functionality and I want it to check to see if the value selected is already in the array, and if so remove it. This would be the case when someone "unchecks" the checkbox.

checkedCodes: any = [];

searchResultsCheckBox = (e) => {
    var row = e.target.parentNode.parentNode;
    var charge = row.getElementsByClassName('chargeList')[0] as HTMLElement;
    var description = row.getElementsByClassName('descriptionList')[0] as HTMLElement;
    this.selectedCode = charge.innerText + " (" + description.innerText + ")";
    if (this.checkedCodes.includes(this.selectedCode)){
      // What should I put here? 
    }
    else {
      this.checkedCodes.push(this.selectedCode);
    }
}

I want something in the if statement to check to see if the selectedCode is already in the array checkedCodes and if so remove it. Any suggestions will help

CBarr
  • 21,475
  • 18
  • 85
  • 119
Justin
  • 347
  • 2
  • 4
  • 14

1 Answers1

0

You want to know how to remove an item from an array? use array.splice()

Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

Pass in the index you want to begin removing at, and then the number of items you want to remove.

var arr = ['one', 'two', 'three', 'four', 'five'];
console.log(arr);

var pos = arr.indexOf('three');
arr.splice(pos, 1);
console.log(arr);

Edit

And just to be clear, here's how you'd modify your code do so this

if (this.checkedCodes.includes(this.selectedCode)){
  var pos = this.checkedCodes.indexOf(this.selectedCode)
  this.checkCodes.splice(pos, 1);
}
CBarr
  • 21,475
  • 18
  • 85
  • 119
  • This isn't what I'm looking for. Your answer would indicate that I would know the position within the array, which I wouldn't. I'm interested in removing the value that matches the incoming one – Justin Mar 11 '19 at 18:35
  • You're saying you want to remove an item from the array, but you have no idea which item it is or how to locate it? Your code has `if (this.checkedCodes.includes(this.selectedCode)){` which suggests that you just found exactly what you want in the array. So now you just need to get the index by doing `this.checkedCodes.indexOf(this.SelectedCode)` – CBarr Mar 11 '19 at 18:38
  • that worked, THANK YOU! – Justin Mar 11 '19 at 18:42