在二维数组中查找比较

时间:2018-05-09 11:23:49

标签: javascript arrays compare shortcuts

我正在尝试为javascript上的帖子列表创建快捷方式。 我有快捷方式和带有类别的帖子。

我需要通过快捷方式过滤帖子。 只有严格的比较:

 ['Boxer', 'Terrier'] !== ['Boxer', 'Terrier', 'Bulldog']
 ['Boxer'] !== ['Boxer', 'Terrier', 'Bulldog']
 ['Boxer', 'Terrier'] === ['Boxer', 'Terrier']
 ['Boxer', 'Terrier'] === ['Terrier', 'Boxer']
 ['Boxer'] === ['Boxer']

我选择了这个选项,但我认为它的代码质量很差:

var allPosts = [
    {
        categories: [
            ['cats'],
            ['Cymric', 'Persian']
        ],
        id: 1,
            title: 'Cats',
            message: 'Cymric, Persian'
        },
        {
            categories: [
                ['dogs'],
                ['Boxer', 'Terrier']
            ],
            id: 2,
            title: 'Dogs',
            message: 'Boxer, Terrier'
        },
        ...
    ]
var shortcutCategories = [
        ['dogs'],
        ['Boxer', 'Terrier']
    ]
var displayedPosts = [];
var displayedPostsId = [];

shortcutCategories.forEach(function (shortcutSetOfCategory) {
    if (shortcutSetOfCategory.length > 1) {
        var internalCompare = false;
        allPosts.forEach(function (post) {
            post.categories.forEach(function (postSetOfCategory) {
                if (postSetOfCategory.length > 1) {
                    shortcutSetOfCategory.every(function (shortcutCategory) {
                        internalCompare = postSetOfCategory.includes(shortcutCategory);
                        return internalCompare;
                    });
                    if (!internalCompare) {
                        return;
                    }
                    displayedPostsId.push(post.id);
                }
            });
        });
    } else {
        allPosts.forEach(function (post) {
            post.categories.forEach(function (postSetOfCategory) {
                if (postSetOfCategory.length === 1) {
                    if (shortcutSetOfCategory[0] === postSetOfCategory[0]) {
                        displayedPostsId.push(post.id);
                    }
                }
            });
        });
    }
});

allPosts.forEach(function (post) {
    var count = 0;
    displayedPostsId.forEach(function (id) {
        if (id === post.id)
            count++;
    });

    if (shortcutCategories.length === count) {
        displayedPosts.push(post);
    }
});

1 个答案:

答案 0 :(得分:1)

我认为您可以使用JSON.stringify来比较二维数组

 certificate: |-
    >    {% for line in certificate.split('\n') %}
    >    {{ line }}
    >    {% endfor %}
    >    {% endif %}
    >    {% if destinationCACertificate is defined %}
    >    destinationCACertificate: |-
    >    {% for line in destinationCACertificate.split('\n') %}
    >    {{ line }}
    >    {% endfor %}
    >    {% endif %}