'How to exclude list of values from array using javascript
I have 3 categories. Each category has own list of items. Each item has two parameters: title and image. I get 5 or 3 random items from all available items and I need a function to be able to exclude items from a specific category.
How to exclude checked categories and how to output images with html?
https://jsfiddle.net/b1Lexf6j/
Here is my code:
function getMultipleRandom(arr, num) {
const shuffled = [...arr].sort(() => 0.5 - Math.random());
return shuffled.slice(0, num);
}
var category_a = [ ['title A1','img/A1.png'],['title A2','img/A2.png'],['title A3','img/A3.png'] ];
var category_b = [ ['title B1','img/B1.png'],['title B2','img/B2.png'],['title B3','img/B3.png'] ];
var category_c = [ ['title C1','img/C1.png'],['title C2','img/C2.png'],['title C3','img/C3.png'] ];
const all = [...category_a, ...category_b, ...category_c];
$("#random").click(function(){
var radioValue = $("input[name='results_number']:checked").val();
$("#results").empty();
$("#results").append(getMultipleRandom(all, radioValue));
$("#nothing").hide();
});
$("#reset").click(function(){
$("#results").empty();
$("#nothing").show();
});
html {
font-size: 16px;
font-family: Roboto, Verdana;
}
button {
border: 0;
background: #3f51b5;
color: #fff;
border-radius: 10px;
padding: 10px 15px;
margin-right: 10px;
cursor: pointer;
}
label {
color: #3f51b5;
margin-top: 20px;
}
input {
float:
}
input:checked {
color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button id="random">Random</button>
<button id="reset">Reset</button>
<label><input type="radio" name="results_number" value="5">5 results</label>
<label><input type="radio" name="results_number" value="3" checked>3 results</label>
<br><br>
<label><input type="checkbox" class="category_a">Exclude category A</label>
<label><input type="checkbox" class="category_b">Exclude category B</label>
<label><input type="checkbox" class="category_c">Exclude category C</label>
<h2>Results</h2>
<ul id="results">
<!-- a list of results should appear here -->
</ul>
<div id="nothing">Select number of results and exclude categories, then click Random button to get values.</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
