如何从数组JavaScript将已排序的值分成2个不同的数组?

时间:2018-09-07 14:06:35

标签: javascript arrays

我有一个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和一个类型B的子数组?

4 个答案:

答案 0 :(得分:2)

如果您只是想获取按类型过滤的数组,那么下面的简单函数将起作用:

/**
 * @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');

答案 1 :(得分:2)

function splitByPropVal(array, prop) {
    return array.reduce(function(acc, item) {
      if (acc[item[prop]] === undefined) acc[item[prop]] = [];
      acc[item[prop]].push(item);
      return acc;
    }, {});
  }

splitByPropVal(articleBody, 'type');

答案 2 :(得分:1)

您可以采用单循环方法和对象,并以类型作为标准进行推送。

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

articleBody.forEach(o => (types[o.type] = types[o.type] || []).push(o));

console.log(types);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 3 :(得分:1)

filter方法返回具有所有与某个谓词匹配的元素的数组的副本。

const typeA = articleBody.filter(a => a.type === 'code');
const typeB = articleBody.filter(a => a.type === 'video');