joehungjohn joehungjohn - 3 months ago 8
Javascript Question

A simple check if selected, if not add to array in Javascript

This function is supposed to take the id of the selected row and check to see if it is in an array or not, if it isn't on the array, add it to the array, otherwise remove it from the array. The problem is I can't seem to get the order of events right. The loop does not run all the way through (because of the breaks) but if I remove the breaks, while the image changing (checkbox) works, the array is still wrong.

I also don't understand why despite declaring the

deleteString = [];
outside of this function, without putting it inside the function, the call of
deleteString.push(orderId);
fails

It seems obvious the problem, on the first run regardless of how big the array is, whether or not the check matches or doesn't match, the rest of the loop won't run. So perhaps I should do a check to wait until the loop is done before using the result of found/not-found.

function passSelection(orderId) {
// check if empty
if (deleteString.length == 0) {
// turn into array
deleteString = [];
// first entry
deleteString.push(orderId);
// mark this row as checked
$("#"+"select-box-"+orderId).attr('src', 'images/red-checked.png');
}
else {
// not the first order
// check if already in array
// get length of array
var delStrLen = deleteString.length;
// loop through array
for (var i = 0; i < delStrLen; i++) {
if (deleteString[i] == orderId) {
// match found, remove from deleteString array
deleteString.splice(i, 1);
// update the row
$("#"+"select-box-"+orderId).attr('src', 'images/unchecked.png');
break;
}
else {
// not in the array
// add to array
deleteString.push(orderId);
// update row
$("#"+"select-box-"+orderId).attr('src', 'images/red-checked.png');
break;
}
}
}
}

Answer

You ought to use indexOf to test existence of elements in an array. indexOf returns the position of the search-item or -1 if the element cannot be found So, here is your code that I have refactored and tested

var deleteString = [];
function passSelection(orderId) {
  // check if empty
  let orderPos = deleteString.indexOf(orderId);
  if (orderPos == -1) {
    // first entry
    deleteString.push(orderId);
    // mark this row as checked
    $("#"+"select-box-"+orderId).attr('src', 'images/red-checked.png');
  }
  else {

    // match found, remove from deleteString array
    deleteString.splice(orderPos, 1);
    // update the row
    $("#"+"select-box-"+orderId).attr('src', 'images/unchecked.png');
  }
}