javascript - 如何将排序后的值从数组 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 的子数组?
解决方案
如果您只是想获得一个按类型过滤的数组,那么像下面这样的简单函数就可以了:
/**
* @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');
推荐阅读
- reactjs - 当输入聚焦时,React Select Async 将光标(插入符号)放在占位符的末尾
- javascript - 在 Reactjs 中绑定数据
- erlang - 在应用程序启动时填充 ETS 表
- r - R通过从数据帧中设置子集来制作数据帧列表
- javascript - 将类型键映射到字符串,然后映射到 Typescript 中的字符串类型
- google-contacts-api - Google Contacts API V3 不返回自动联系人条目的标题
- javascript - 易趣汽车列表的语言?
- c# - 如何在 UWP 应用程序中绘制波形?
- python - 当像素 hsv 值在特定范围内时,如何更改图像颜色?
- c# - asp .net 服务 2 网络