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:
- Why this sorting isn't working for the second array? (I'm using the same array.sort function for both of these arrays)
- 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)