1

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.

Cogicero
  • 1,386
  • 2
  • 15
  • 31
  • 3
    Why no `.trim()` on `$('span.query').html()`? Are you sure the `index` in `removeElement` is `-1`, or is this [Chrome's JavaScript console being lazy about evaluating arrays](https://stackoverflow.com/q/4057440/4642212) (put a `.slice()` inside every `console.log(queries)` call to be sure)? – Sebastian Simon Dec 27 '20 at 06:53
  • Thanks! I already trimmed that before storing it in the span.Your point about Chrome issue is probably what is going on! I have been at this for well over two hours. How would I go about the .slice() thing please? I already tried `console.log(queries.slice(0))` and it made no difference. – Cogicero Dec 27 '20 at 06:57
  • P.S. Also tried `console.log(queries.slice())` and `console.log(queries.join())` and `console.log(queries.concat())` and `console.log(JSON.parse(JSON.stringify(queries)))`. The issue isn't simply with console.log however. The array is stringified for storage (stored in the input text field) and it is similarly not updating when an item is removed from it. It seems the browser is simply ignoring any changes made to the array. Also cleared my browser cache. – Cogicero Dec 27 '20 at 07:08
  • 1
    @user4642212 I just finally solved this by JSON.stringify() once more before console.log and also JSON.stringify to save it back into the input. Your link about the Chrome bug helped a great deal! If you post it as an answer I can accept it. – Cogicero Dec 27 '20 at 07:26

0 Answers0