I have an array of years that I am using ECMAScript to filter through to find matches of animals that fall within a range between two years from another array of years.
The for loop I have inside my callback called buildList(animal) is not working in the fact that it is iterating over every year and ignoring the conditional I have placed inside the for loop.
I have worked with jQuery using two $.each, one to iterate across the years, and a nested $.each to compare the current year with the year of the animal.
** My comments in the code were stripped apparently. The expected result is to have each animal displayed but if their animaldate falls within the animalyears range then display the animaldate in and show it falls between the two years.
The example function I provided called buildList_example() demonstrates the expected outcome but is using hard coded iterators in the conditional for animalyears[0]
// array of years
let animalyears = ['1970', '1980', '1990', '2000', '2001']
// static data
let data = {
"animals": [{
"animaldate": "1972",
"title": "Sparky"
},
{
"animaldate": "1975",
"title": "Max"
},
{
"animaldate": "1980",
"title": "Fido"
},
{
"animaldate": "1981",
"title": "Frank"
},
{
"animaldate": "1994",
"title": "Fiona"
}
]
}
var allAnimals = data.animals;
var animalList
allAnimals.map((animal) => buildList(animal))
function buildList(animal) {
for (var i = 0; i < animalyears.length; i++) {
animalList += `<div class="animal">`
if (animal.animaldate >= animalyears[i] && animal.animaldate < animalyears[i + 1]) {
animalList += `<h1> ${animal.animaldate} </h1>`
animalList += `<p> ${animal.title} </p>`
animalList += `<p> Falls between ${animalyears[i]} and ${animalyears[i + 1]}</p>`
} else {
animalList += `<p> ${animal.animaldate} </p>`
animalList += `<p> ${animal.title} </p>`
}
animalList += `</div>`
}
}
function buildList_example(animal) {
animalList += `<div class="animal">`
if (animal.animaldate >= animalyears[0] && animal.animaldate < animalyears[0 + 1]) {
animalList += `<h1> ${animal.animaldate} </h1>`
animalList += `<p> ${animal.title} </p>`
animalList += `<p> Falls between ${animalyears[0]} and ${animalyears[0 + 1]}</p>`
} else {
animalList += `<p> ${animal.animaldate} </p>`
animalList += `<p> ${animal.title} </p>`
}
animalList += `</div>`
}
var output = document.getElementById("output")
output.innerHTML = animalList
.animal {
border: 1px solid black;
display: flex;
flex-flow: column;
}
<div id="output">
</div>