1

So I want to save the titles array formatted with line breaks and index of each element.

When I save the 'formatted' object with fs all I get in the file is 'undefined'.

Also, this code is probably really messy and could be simplified, what should I change?

            const $ = cheerio.load(body);
            let titles = [];
            $('div.collection.clearfix').each((i, el) => {
                const title = $(el)
                    .text()
                    .replace(/\n/g, '')
                    .trim()
                    .replace(/ /g, ',');
                titles.push(title);
            })

            let formatted = titles.forEach((i, title) => {
                return title + '. ' + i + '\n'
            });
            fs.writeFile('titles.txt', formatted, (e) => {
                if (e) console.error(e)
            })

1 Answer 1

3

You expect

            let formatted = titles.forEach((i, title) => {
                return title + '. ' + i + '\n'
            });

to return an array.

However, forEach returns undefined.

You are looking for titles.map, which returns an array. Then, you can join all the elements using Array.prototype.join() to turn it into a single string

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.