I have the following javascript function to remove an item from an array, but the index search always returns -1 no matter what I searching for. I am calling it from within a jQuery "on" click function.
function removeElement(array, elem) {
let index = array.indexOf(elem);
if (index > -1) {
array.splice(index, 1);
}
}
$('div.test').on('click', 'a.btn', function(e){
e.preventDefault();
let text = $('span.query').html().trim();
let queries = JSON.parse($('.search').val().trim());
console.log(queries); // This line shows the same results
removeElement(queries,text);
console.log(queries); // as this line
});
where $('span.query')
contains the text def
and $('.search')
is an input text field that contains an array that has been JSON-stringified
["abc","def","ghij","klmn"]
Regardless of what is used to search my queries array (parsed from the above), the index is always -1 and the result (after an element "removal" attempt) is always
["abc", "def", "ghij", "klmn"]
Any ideas what might be going wrong here? I have been tearing my hair out over this.