每月做過幾次,兩集合之配對 forEach、filter 用法

 

如下例,其結果會列出針對每個月份做過幾次

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
</head>

<body>
    <script>
        var monthName = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
        var collection = [
            { months: '01', count: 1 }, 
            { months: '03', count: 3 },
            { months: '12', count: 12 },
        ];
        var result = [];

        monthName.forEach(element => {
            let subCollection = collection.filter(n => n.months == element);
            if (subCollection.length != 0) {
                result.push(subCollection[0].count);
            }
            else {
                result.push(0);
            }
        });

        console.log(result);
    </script>
</body>

</html>

執行結果為

說明:

針對 a 集合裡的每個元素為基底,去過濾 b 集合所相符合條件之 b 子集合。