I am working on the following problem:
If user selects any of Toyota, Mazda, and Nissan Then remove All from makeArr array if exist
and
If user selects All Then remove any of Toyota, Mazda, and Nissan from makeArr array if they exist
I tried to use this code
makeArr.splice($.inArray("All", makeArr), 1);
in the else part but it is not working!
var makeArr = [];
$(".btn-primary").on("click", function() {
let make = $(this).data('make');
if (make === "All") {
var idx = $.inArray(make, makeArr);
if (idx == -1) {
makeArr.push(make);
} else {
makeArr.splice(idx, 1);
}
} else {
// makeArr.splice($.inArray("All", makeArr), 1);
var idx = $.inArray(make, makeArr);
if (idx == -1) {
makeArr.push(make);
} else {
makeArr.splice(idx, 1);
}
}
console.log(makeArr);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<div class="container p-2">
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-primary" data-make="Toyota">Toyota</button>
<button type="button" class="btn btn-primary" data-make="Mazda">Mazda</button>
<button type="button" class="btn btn-primary" data-make="Nissan">Nissan</button>
<button type="button" class="btn btn-primary" data-make="All">All</button>
</div>
</div>
makeArr.splice($.inArray("All", makeArr), 1);if "All" doesn't exists, then inArray returns -1 and it return the last element from the array. seemakeArr.splice(-1, 1);, So, you should check before All element existing or not