skip to Main Content

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


  1. You have to push in the array favFilms like this and it works as you want.

    else if (typeof item === 'string') {
        favFilms.push(item);
    }
    

    Also initiliaze these arrays outside of the map function

    let film = [];
    let favFilms = [];
    
    Login or Signup to reply.
  2. 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 assigning favFilms = [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:

    const data = [{marvel: {name: 'Thor',film: 'Thor',nickName: 'god of thunder',},dc: {name: 'Joker',film: ['Batman', 'Joker'],},},'Iron-Man','Super-man',];
    
    const film = data.flatMap(item =>
        item.marvel ? item.dc.film.concat(item.marvel.film) : item
    );
    console.log(film);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search