Home > Enterprise >  I would like to avoid using `.flat()` and use `.reduce` instead in JavaScript
I would like to avoid using `.flat()` and use `.reduce` instead in JavaScript

Time:02-06

I have

  • an array of strings const rooms = ['roomA', 'roomB', 'roomC'].
  • an object that has
const roomOccupants = { 
  'roomA': [{name: 'player1'}, {name: 'player555'}], 
  'roomB': [{name: 'player2'}, {name: 'player3'}] 
}

I have added the players from roomA & roomB to a new room say roomABC using the map function below however roomABC needs to be flattened using .flat() array method bc the returned value structure is [{}, {}], [{}, {}]. I was wondering if there is a way that I could avoid using .flat() maybe using .reduce() could achieve that but I was not able to figure it out.

const roomABC = rooms.map((roomName) => {
  return roomOccupants[roomName];
});

I need the output to be as follows. No need for unique items/order of the items in the array. Thanks in advance.

const roomABC = [{name: 'player1'}, {name: 'player2'}, {name: 'player3'}, {name: 'player555'}]

CodePudding user response:

const rooms = ['roomA', 'roomB', 'roomC'];

const roomOccupants = { 
  'roomA': [{name: 'player1'}, {name: 'player555'}], 
  'roomB': [{name: 'player2'}, {name: 'player3'}] 
};

const roomABC = rooms.reduce((acc,curr) => {
  if(roomOccupants[curr]){
    acc = acc.concat(roomOccupants[curr]);
  }
  return acc;
},[]);

console.log(roomABC);

/* Prints :
[
  {
    "name": "player1"
  },
  {
    "name": "player555"
  },
  {
    "name": "player2"
  },
  {
    "name": "player3"
  }
]
*/

Here acc is the accumulated result and curr is the current value.

The reducer function gets called for every element of the rooms array. So in the above code snippet, curr will take values "room1", "room2", and "room3".

We start with an empty list, [] as the initial value of acc.

The function checks if roomOccupants[curr] exists and if it does, concatenates it's value with the previous value of acc.

Hope this helps!

  • Related