获取 JavaScript 中相同对象的总数
javascriptweb developmentfront end technologyobject oriented programming
假设,我们有一个对象数组,描述一些航班的航线,如下所示 −
const routes = [ { flyFrom: &"CDG", flyTo: &"DUB", return: 0, }, { flyFrom: &"DUB", flyTo: &"SXF", return: 0, }, { flyFrom: &"SFX", flyTo: &"CDG", return: 1, } ];
我们需要计算 return − 0 的次数和 return: 1 的次数。
最终输出应如下所示 −
for the cases where return: 0 appears 2 times --- 1 Stop for the cases where return: 1 appears 1 time --- Non-stop
示例
其代码为 −
const routes = [ { flyFrom: "CDG", flyTo: "DUB", return: 0, }, { flyFrom: "DUB", flyTo: "SXF", return: 0, }, { flyFrom: "SFX", flyTo: "CDG", return: 1, } ]; const displaySimilar = arr => { const count = {}; arr.forEach(el => { count[el.return] = (count[el.return] || 0) + 1; }); Object.keys(count).forEach(key => { for(let i = 0; i < count[key]; i++){ if(key === '0'){ console.log('1 Stop'); } else if(key === '1'){ console.log('Non-stop'); }; } }) }; displaySimilar(routes);
输出
控制台中的输出将是 −
1 Stop 1 Stop Non-stop