Curtis
Curtis

Reputation: 2704

Splice JavaScript array

Here's my attempt at trying to remove a value from an array dynamically

$('.btn-remove').click(function() {
    var players = ["compare","13076","13075","13077","12755"];
    var removePlayer = $(this).data('player');
    var idx = $.inArray(removePlayer, players);
    if (idx != -1) {
        players.splice(idx, 1);
    }
    window.location = "/" + players.join('/');
})

For example, $(this).data('player') could equal 13077 and i'd want it to remove that value from the array and then redirect to the url which is attached to the window.location variable

Upvotes: 1

Views: 109

Answers (1)

apsillers
apsillers

Reputation: 115920

The issue here is that .data converts the player data string value to a number:

Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null). A value is only converted to a number if doing so doesn't change the value's representation... The string value "100" is converted to the number 100.

In your example, you're doing

$.inArray(13077, ["compare","13076","13075","13077","12755"]);

rather than

$.inArray("13077", ["compare","13076","13075","13077","12755"]);

You must either convert the data value back to a string (e.g., removePlayer += "") or fill the array with number values instead of strings.

Upvotes: 2

Related Questions