假设我们有一个对象数组,描述了一些像这样的航班的路线-
const routes = [ { flyFrom: "CDG", flyTo: "DUB", return: 0, }, { flyFrom: "DUB", flyTo: "SXF", return: 0, }, { flyFrom: "SFX", flyTo: "CDG", return: 1, } ];
我们需要计算返回的次数-0和返回的次数: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