以对象为初始值的数组归约

Can anyone explain what's going on with reduce function in the below example, I have an object with keys and empty arrays as the initial value for reduce method, I would like to have step by step explanation inside reduce method

initExercises = {
  shoulders: [],
  chest: [],
  arms: [],
  back: [],
  legs: []
}

exercises = [

  {
    id: "overhead-press",
    title: "Overhead Press",
    description: "Delts exercise...",
    muscles: "shoulders"
  },

  {
    id: "dips",
    title: "Dips",
    description: "Triceps exercise...",
    muscles: "arms"
  },

  {
    id: "barbell-curls",
    title: "Barbell Curls",
    description: "Biceps exercise...",
    muscles: "arms"
  },

  {
    id: "bench-press",
    title: "Bench Press",
    description: "Chest exercise...",
    muscles: "chest"
  },

  {
    id: "pull-ups",
    title: "Pull Ups",
    description: "Back and biceps exercise...",
    muscles: "back"
  },

  {
    id: "deadlifts",
    title: "Deadlifts",
    description: "Back and leg exercise...",
    muscles: "back"
  },

  {
    id: "squats",
    title: "Squats",
    description: "Legs exercise...",
    muscles: "legs"
  }

];


console.log(
  exercises.reduce((acc, curr) => {
    const {
      muscles
    } = curr;
    acc[muscles] = [...acc[muscles], curr] //what's happening here?
    return acc;
  }, initExercises)
)
评论
  • 正经人
    正经人 回复

    Spread syntax, acc[muscles] = [...acc[muscles], curr] equal to acc[muscles] = acc[muscles].concat(curr), e.g. adding current exercise to group with key muscles