This code is supposed to log to the console which books + amount of each book is still at the library at the end of the day. Array 1 shows the books + amount at the start of day 1 and array 2 shows which books the library gets back ("teruggave") and which books the library loans out ("uitlening").
When the a book gets loaned out the "aantal" value of the book should go -1 while it should go +1 when the library gets a book back. The moment "aantal" reached 0, that book should be deleted from array 1. This is the part that all went well.
I also need to add the book object key "ISBN" + aantal 1 to the catalogus when that book is not at the library (so not in catalogus). I tried this but I can’t seem to get it to work. Either it keeps loading endlesly when I try to log it to the console or I get the the same book multiple times with the same "aantal" logged.
The result should be 5 books, 4 should have aantal:1 and 1 should aantal: 3.
I tried searching for an answer and tried using .include() for example to check if the ISBN[i] (so the object key it’s looking at) was available in array 1 or not. This didn’t work tho and I got the same result as I get with the code below.
for (let i = 0; i < dagverloop.length; i++) {
for (let j = 0; j < catalogus.length; j++) {
if (dagverloop[i].handeling === "uitlening" && dagverloop[i].ISBN === catalogus[j].ISBN) {
catalogus[j].aantal--;
} else if (dagverloop[i].handeling === "teruggave" && dagverloop[i].ISBN === catalogus[j].ISBN) {
catalogus[j].aantal++;
} else if (dagverloop[i].handeling === "uitlening" && catalogus[j].aantal === 0) {
catalogus.splice(0, 1);
} else if (dagverloop[i].handeling === "teruggave" && dagverloop[i].ISBN != catalogus[j].ISBN) {
catalogus.push({
ISBN: dagverloop[i].ISBN,
aantal: 1
});
}
}
}
console.log(catalogus);
<script>
let catalogus = [{
ISBN: "978-1449355739",
aantal: 1,
},
{
ISBN: "978-0596806750",
aantal: 2,
},
{
ISBN: "978-0596805524",
aantal: 1,
},
{
ISBN: "978-1491905012",
aantal: 1,
},
{
ISBN: "978-0596008642",
aantal: 3,
},
{
ISBN: "978-0596004897",
aantal: 2,
},
];
const dagverloop = [{
ISBN: "978-0596806750",
handeling: "uitlening",
},
{
ISBN: "978-1491905012",
handeling: "teruggave",
},
{
ISBN: "978-0596805524",
handeling: "uitlening",
},
{
ISBN: "978-1449319243",
handeling: "teruggave",
},
{
ISBN: "978-1491905012",
handeling: "uitlening",
},
{
ISBN: "978-0596004897",
handeling: "uitlening",
},
{
ISBN: "978-1491908426",
handeling: "teruggave",
},
{
ISBN: "978-1449319243",
handeling: "uitlening",
},
{
ISBN: "978-0596004361",
handeling: "teruggave",
},
{
ISBN: "978-1491905012",
handeling: "uitlening",
},
{
ISBN: "978-1449355739",
handeling: "uitlening",
},
];
</script>
2
Answers
You need to
Using a proper data structure is 99% of success. In you case, it’s a
Map
ISBN => count, which you can create like this:Once this is done, the rest is easy:
Now convert that map back to the list of records:
Handling zero values left as an exercise (hint: put
.filter
before.map
above).