首页 > 解决方案 > 如何将排序后的值从数组 javascript 拆分为 2 个不同的数组?

问题描述

我有一个javascript示例,其中我有一个数组articleBody,我试图从键“type”中对值进行排序我已经准备好排序函数,如下所示:

大批:

var articleBody = [
    {
        "type": "code"  
    },{
        "type": "video"  
    },{
        "type": "code"  
    },{
        "type": "video"  
    },{
        "type": "code"  
    },{
        "type": "video"  
    }
]

排序功能:

articleBody.sort(function(a, b) {
    var typeA = a.type.toUpperCase(); 
    var typeB = b.type.toUpperCase(); 
    if (typeA < typeB) {
        return -1;
    }
    if (typeA > typeB) {
        return 1;
    }
    return 0;
});

如何获得一个 typeA 的子数组和一个 typeB 的子数组?

标签: javascriptarrays

解决方案


如果您只是想获得一个按类型过滤的数组,那么像下面这样的简单函数就可以了:

/**
 * @param {Array} arr - the array being filtered
 * @param {String} type - value of the type being sought
 * @returns array filtered by type
 */
function subArrayByType(arr, type) {
    return arr.filter(el=>el.type == type);
}

const codes = subArrayByType(articleBody, 'code');
const videos = subArrayByType(articleBody, 'video');

推荐阅读