0

I'm trying to sort my array of Star Wars episodes by episode ID. I faced a strange problem. I have first array (marked as "1" on screenshot) and second array (marked as "2" on screenshot).

The first one is just data pasted into code:

const test = [
        { title: 'The Empire Strikes Back', episode_id: 5 },
        { title: 'A New Hope', episode_id: 4 },
        { title: 'Attack of the Clones', episode_id: 2 },
        { title: 'Return of the Jedi', episode_id: 6 },
        { title: 'The Phantom Menace', episode_id: 1 },
        { title: 'Revenge of the Sith', episode_id: 3 },
      ];

The second one is function which takes an array of endpoints (filmsArray) and then gets the specific title and episode_id from all endpoints, and then pushing it into array as object and returns that array.

const handleGetFilms = (filmsArray) => {
    const titlesArray = [];
    filmsArray.forEach(async (film) => {
      const {
        data: { title, episode_id },
      } = await axios.get(film);
      titlesArray.push({ title, episode_id });
    });
    return titlesArray;
  };

As you can see on the screenshot - sorting for the first array (which is just data pasted into code) works well, but sorting for the second (which is dynamic data) is not working at all. Because of that I have two questions:

  1. Why this sorting isn't working for the second array? (I'm using the same array.sort function for both of these arrays)
  2. Why there's a difference between console.log for those two arrays? Shouldn't they be the same?(Marked as green on the screenshot)

EDIT: I'm adding the sorting code:

arrayName.sort((a, b) => a.episode_id - b.episode_id)

enter image description here

mdzialo
  • 17
  • 5
  • The console prints a static preview of the object at the time of execution of `console.log`. If you later click onto the object/array in the console, the reference to that array is loaded and the data is refreshed. – ssc-hrep3 Apr 07 '21 at 11:11
  • can you post the code snippet of sorting logic? – Ravikumar Apr 07 '21 at 11:12
  • `filmsArray.forEach(async` doesn't work as you expect. It fires your promises and then moves on without waiting for them to complete. You need a `for` loop here. – georg Apr 07 '21 at 11:14
  • 2
    https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop – georg Apr 07 '21 at 11:15
  • @Ravikumar I added the sorting logic. – mdzialo Apr 07 '21 at 11:18

1 Answers1

1

You must change foreach with normal for loop or other options. forEach loop doesn't support for async await because forEach expects a synchronous function only.