My program:
const data = [
{
marvel: {
name: 'Thor',
film: 'Thor',
nickName: 'god of thunder',
},
dc: {
name: 'Joker',
film: ['Batman', 'Joker'],
},
},
'Iron-Man',
'Super-man',
];
let film = [];
const myFav = data.map(item => {
if (typeof item === 'object') {
let jokerDcfilms = [];
let favCharacterFilms = [];
let thorMarvelFilm = item.marvel.film;
jokerDcfilms.push(item.dc.film);
const dcFilms = jokerDcfilms.flat(1);
favCharacterFilms = [...dcFilms, thorMarvelFilm];
} else if (typeof item === 'string') {
let favFilms = [];
favFilms = [item];
}
});
film = [...favCharacterFilms, ...favFilms];
console.log(film);
Expected output is:
[ 'Batman', 'Joker', 'Thor', 'Iron-man', 'Super-man' ]
Current output is:
[ 'Batman', 'Joker', 'Thor', 'super-man' ]
Why am I not getting expected output? I just want to insert all films in the data to a array and should print that array.
Note: Changing/altering data is not an option.
2
Answers
You have to push in the array favFilms like this and it works as you want.
Also initiliaze these arrays outside of the map function
You’ve defined
favFilms
as a blockscoped variable, so it is not accessible outside that block. Even if you would have defined it with a larger scope, you still reset it to have just one item, by assigningfavFilms = [item]
. So whatever was already collected in an array, is now lost.You should not use
.map
if you don’t intend to use the array it returns. However, in this case it would actually be a good idea to capture the array it returns.Flatten the array that you get returned: