0

Following continues the each even when I hit the line with return. How do you return from a method from inside an $.each?

removeFromArray: function (text, arr) {
        $.each(arr, function (value, key) {
            if (key.text == text) {
                arr.splice(value, 1);
                return;
            }
        });
    } 
Thomas Segato
  • 4,567
  • 11
  • 55
  • 104
  • Why no simple `for` loop? If `$` is jQuery then have a look at the documentation of [`$.each()`](https://api.jquery.com/jquery.each/) for an answer. – Andreas Oct 07 '17 at 13:55
  • It is. Just realized its just standard jquery. Thanks. Feel free to post an answer. – Thomas Segato Oct 07 '17 at 14:06

1 Answers1

1

It is not really recommended to use Vue with jQuery (link), also, Vue tends not to play nice with jQuery plugins (works though, link). This is only my personal preference, that I don't use jQuery with Vue at all, so here's what I suggest.

Method 1: map and indexOf (assuming duplicates exist in arr)

removeFromArray(text, arr) {
    let idx = arr
        .map((item)=>item.text)
        .indexOf(text)

    if (idx !== -1) {
        arr.splice(idx, 1)
    }
}

Method 2: Reduce (assuming duplicates do not exist in arr)

removeFromArray(text, arr) {
    arr = arr.filter((item) => item.text !== text)
}
kevguy
  • 4,328
  • 1
  • 24
  • 45