JS 减速器到 return 对象

JS reducer to return object

我想从下面的代码中得到像“{ sitting: 3, standing: 2 }”这样的输出,有人能帮忙吗?

 var desks = [
  { type: 'sitting' },
  { type: 'standing' },
  { type: 'sitting' },
  { type: 'sitting' },
  { type: 'standing' }
];

var deskTypes = desks.reduce(function() {
    //Acutal code.
}, { sitting: 0, standing: 0 });

你可以这样做。确保在每次迭代后 return types 累加器对象。

const desks = [
    { type: 'sitting' },
    { type: 'standing' },
    { type: 'sitting' },
    { type: 'sitting' },
    { type: 'standing' },
]

const deskTypes = desks.reduce((types, desk) => {
    types[desk.type]++
    
    return types
}, { sitting: 0, standing: 0 })

console.log(deskTypes)

只需使用Array.reduce即可完成。

const desks = [
  { type: 'sitting' },
  { type: 'standing' },
  { type: 'sitting' },
  { type: 'sitting' },
  { type: 'standing' }
];

const result = desks.reduce((acc, cur) => {
  if (acc[cur.type]) {
    acc[cur.type] ++;
  } else {
    acc[cur.type] = 1;
  }
  return acc;
}, {});
console.log(result);

let deskTypes = desks.reduce(
  (types, { type }) => {
    types[type]++;
    return types;
  },
  { sitting: 0, standing: 0 }
);
const desks = [
  { type: "sitting" },
  { type: "standing" },
  { type: "sitting" },
  { type: "sitting" },
  { type: "standing" },
];

const deskTypes = desks.reduce(
  (acc, item) => {
    
    if (item.type === "sitting") {
      acc.sitting++;
    } else {
      acc.standing++;
    }

    return acc;
  },
  { sitting: 0, standing: 0 }
);

console.log(deskTypes);