yaboylino
yaboylino

Reputation: 45

Getting stuck with filtering in javascript node express

When i am trying the first method with (age => age.Book === book && age.Chapter === 1) my filter works.

When i try (age => age.Book === book && age.Chapter === chapter) it won't work.

So when i don't use a variable at chapter. it can be a number or string. then it's ok. but when i use my variable chapter. it won't work.

all my chapters are numbers. when i changed one chapter in an string (word not number) then my variable chapter did work.

Can somebody explain how i get my variable to work?

app.get("/book/:bookTitle/:bookChapter/", function(req, res){
    const book = req.params.bookTitle;
    const chapter = req.params.bookChapter;
    const verse = req.params.bookVerse;
    const text = req.params.bookText;

    const getBook = verseList.filter(age => age.Book === book && age.Chapter === 1);

    const getBook = verseList.filter(age => age.Book === book && age.Chapter === chapter);

Upvotes: 2

Views: 142

Answers (2)

Ido Cohen
Ido Cohen

Reputation: 800

For the slight chance you missed it.. you can't declare same name twice.

And your code should work as long they both are the same type!

For example:

const array = [];
for (let i=0; i < 100; i++) {
    array[i] = ({
        Book: "a"+Math.round(i/10),
        Chapter: (i%10) + 1
    });
}
console.log(array);
const book = "a3";
// const chapter = "3";//This doesn't work for the second filter!
const chapter = 3;

const getBook = array.filter(age => age.Book === book && age.Chapter === 1);
console.log(getBook);
const getBook2 = array.filter(age => age.Book === book && age.Chapter === chapter);
console.log(getBook2);

Upvotes: 0

Ben West
Ben West

Reputation: 4596

You've almost got it. req.params.bookChapter is a string but the chapters in the array are numbers. So just convert req.params.bookChapter into a number as well.

const chapter = Number( req.params.bookChapter );

Upvotes: 1

Related Questions