Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I try to write a code that will create a file with an amount of unique random jokes using this npm and Environment Variables in an env file. I get a file with random jokes but I can't filter them to be unique.

here is my code:
JavaScript
let oneLinerJoke = require("one-liner-joke");
require("dotenv").config();
let fs = require("fs");
var getRandomJokeWithTag = oneLinerJoke.getRandomJokeWithTag(
  `${process.env.JOKE_SUBJECT}`
);

let arrayJokes = [];
let i = 0;
let counter = 0;
let amount = parseInt(`${process.env.JOKE_AMOUNT}`);
while (i < amount) {
  let joke = oneLinerJoke.getRandomJokeWithTag(process.env.JOKE_SUBJECT);
  if (!arrayJokes.includes(joke.body)) {
    arrayJokes.push(joke.body + "\n");
    i++;
  }
}
const createFile = fs.writeFile("/created_files/jokes.txt",
  arrayJokes.toString().replace(/,/g, ""),(err) => {
    if (err) throw err;
    console.log("The file has been saved!");
  }
);


What I have tried:

I tried in my code using includes but it doesn't seem to work
Posted
Comments
Richard MacCutchan 8-Jun-22 9:30am    
You need to examine exactly what happens at the line:
if (!arrayJokes.includes(joke.body)) {

to see why it is allowing duplicates.
canvas_newbi 8-Jun-22 9:33am    
I tried that. Can it be something with node.js? that because everything in node.js is async maybe writing code in a normal js way is wrong?
Richard MacCutchan 8-Jun-22 9:47am    
What exactly did you seen when you checked this?
canvas_newbi 8-Jun-22 10:07am    
I printed every time a new question appeared and all the element in the array. every time I find that the joke and an element in the array has the same text and the program consider this as two different values (includes returned false).
Richard MacCutchan 8-Jun-22 10:13am    
This could be due to the fact that you are adding a newline character to the string before pushing it into the array. That extra character may mean that the strings are not exactly the same.

I just texted this and it is definitely the problem.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900