使用.map且条件评估为true时加1

时间:2019-05-01 15:20:40

标签: javascript array.prototype.map

当我使用.map遍历数组myClasses且数组中的status等于'Open'或'In Progress'增量时,我很难加1一个数字乘以1。我的目标是拥有“公开”或“进行中”课程的总数

这是我当前正在做的事情

myClasses.map(a => (a.status === ('Open' || 'In Progress') ? 'Yes' : 'No'))

当前,当一个类是Open或In Progress时,我只输出yesno,但我希望能够向数字变量添加1或0。

这是myClasses数组包含的内容

0: {id: "0000AK",  type: "Elective", status: "Open"       } 
1: {id: "597WUK",  type: "Core",     status: "Closed"     } 
2: {id: "082HCE",  type: "Core",     status: "In Progress"} 
3: {id: "091HSN",  type: "Elective", status: "Canceled"   } 
4: {id: "038GAQ",  type: "Core",     status: "Open"       } 

现在我的输出看起来像这样Yes,No,Yes,No,Yes,而不是我希望输出是3

有什么建议吗?

4 个答案:

答案 0 :(得分:3)

如果只是计数,您可以简单地使用filter并获取返回的数组的length

const myClasses = [{id:"0000AK",type:"Elective",status:"Open"},{id:"597WUK",type:"Core",status:"Closed"},{id:"082HCE",type:"Core",status:"In Progress"},{id:"091HSN",type:"Elective",status:"Canceled"},{id:"038GAQ",type:"Core",status:"Open"}];

const count = myClasses.filter(a => a.status === 'Open' || a.status === 'In Progress').length

console.log(count)

答案 1 :(得分:2)

您可以将计数纳入三元组的真实部分。

var myClasses = [{ id: "0000AK", type: "Elective", status: "Open" }, { id: "597WUK", type: "Core", status: "Closed" }, { id: "082HCE", type: "Core", status: "In Progress" }, { id: "091HSN", type: "Elective", status: "Canceled" }, { id: "038GAQ", type: "Core", status: "Open" }],
    count = 0,
    result = myClasses.map(({ status }) => status === 'Open' || status === 'In Progress'
        ? (count++, 'Yes')
        : 'No'
    );

console.log(count);
console.log(result);

要获得计数,您可以减少数组。如果您想检查更多的值,可以使用数组或Set并检查数据结构是否包含元素。

var myClasses = [{ id: "0000AK", type: "Elective", status: "Open" }, { id: "597WUK", type: "Core", status: "Closed" }, { id: "082HCE", type: "Core", status: "In Progress" }, { id: "091HSN", type: "Elective", status: "Canceled" }, { id: "038GAQ", type: "Core", status: "Open" }],
    wanted = ['Open', 'In Progress'],
    count = myClasses.reduce((c, { status }) => c + wanted.includes(status), 0);

 console.log(count);

答案 2 :(得分:1)

那又如何呢?数组减少

const data = [
  { id: '0000AK', type: 'Elective', status: 'Open' },
  { id: '597WUK', type: 'Core', status: 'Closed' },
  { id: '082HCE', type: 'Core', status: 'In Progress' },
  { id: '091HSN', type: 'Elective', status: 'Canceled' },
  { id: '038GAQ', type: 'Core', status: 'Open' }
];

const res = data.reduce((acc, cur) => {
  const status = cur.status;
  if (status === 'Open' || status === 'In Progress') {
    return acc + 1;
  }
  return acc;
}, 0);
console.log(res);

答案 3 :(得分:0)

我建议您使用reduce()而不是map()

var count = myClasses.reduce((accumulator, item) => {
    if (item.status == 'Open' || item.status == 'In Progress') {
        return accumulator + 1;
    }
    return accumulator;
}, 0);

请注意,我还如何修改if语句中的条件以与所需的两个值进行比较。