Console.log and return give me different results

I’m trying to get an array of seasons from the breaking bad API

But I can’t return the seasons, return and console.log give me different results

Here’s the output when I use console.log

here’s the output when I return the values

And here’s my code:

    .then((response) => {
        return response.json()
    .then((data) => { return data })
    .then((data) => {
        for (const ele of data) {
            // First select Breaking Bad series
            // Because the API Has "Better Call Saul as well"
            if (ele.series === "Breaking Bad") {
                // Select all seasons to append them to a dropdown menu
                if (ele.season != null) {
                    let season = ele.season;
                    // console.log(season)
                    return season;

I want to create an array of all seasons from all objects, and then extract duplicate seasons, to append them to the DOM

As soon as a return is executed, the function stops, so it’s normal that if you have a return inside a loop the loop stops


So how can I pass the data I want to the next then() ?

If you want to keep your loop in tact,

  1. Make an empty array before the loop
  2. Change the console.log you’ve got to a push() call on the array from step 1
  3. After the loop, return the array from step 1

Buuuut if I were writing this code then I would use a combination of array methods which I find more readable.

  .then((res) => res.json())
  .then((episodes) => {
    // Take the array of episodes
    const seasons = episodes
      // and only keep the Breaking Bad episodes
      .filter((episode) => episode.series === "Breaking Bad")
      // and only keep the episodes with an affiliated season
      .filter((episode) => episode.season)
      // and convert those episode objects to their season value
      .map((episode) => episode.season);

    // Do stuff with the seasons array
1 Like

That was really helpful, Thank you so much

By the way, the simplest way to do deduplication I’ve seen is to throw the array into a Set, and then get it back as an array via spread (this requires ES6).

const duplicates = [1, 1, 1, 1, 2, 2, 2, 3, 4, 6, 2, 1, 3, 4, 6];
const deduped = [ Set(duplicates)];
console.log(deduped); // [1, 2, 3, 4, 6]
1 Like

That’s really insightful and cool! Thanks :star_struck:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.