javascript - 如何对数组进行分类并形成新数组
问题描述
在我的项目中,我需要对一个数组进行分类并将其转换为另一种类型的数组。我遇到的困难是没有办法使用简洁高效的执行。以下是我的输入和输出:
const input = [{
"type": 1,
"color": "Red(268)"
},
{
"type": 1,
"color": "Blue(583)"
},
{
"type": 2,
"color": "Blue(185)"
},
{
"type": 4,
"color": "Red(326)"
},
{
"type": 4,
"color": "Blue(967)"
},
{
"type": 5,
"color": "Red(863)"
}
]
const output = [
"Type 1: Red(268), Blue(583)",
"Type 2: Blue(185)",
"Type 4: Red(326), Blue(967)",
"Type 5: Red(863)"
]
以下是我的方法。我用set()找出类型的个数,然后用for循环把它转成字符串压入数组,但是不能连续执行,所以我的函数不能得到正确的结果,而且是效率不高。
this.ty = 1;
this.result = [];
const set = new Set();
const length = input.filter(item => !set.has(item.type) ? set.add(item.type) : false).length + 1;
for (let i = 1; i < length; i++) {
const temp = input.filter(x => {
return x.type === ty;
})
if (temp.length < 2) {
this.result.push(`Type ${ty}: ${temp[0].color}`);
} else {
this.result.push(`Type ${ty}: ${temp[0].color}, ${temp[1].color}`);
}
this.ty = i + 1;
}
这个问题困扰了我很久。有人可以提供一种更简单的方法来转换这个数组吗?谢谢您的帮助。
const input = [{
"type": 1,
"color": "Red(268)"
},
{
"type": 1,
"color": "Blue(583)"
},
{
"type": 2,
"color": "Blue(185)"
},
{
"type": 4,
"color": "Red(326)"
},
{
"type": 4,
"color": "Blue(967)"
},
{
"type": 5,
"color": "Red(863)"
}
]
console.log('input', input);
this.ty = 1;
this.result = [];
const set = new Set();
const length = input.filter(item => !set.has(item.type) ? set.add(item.type) : false).length + 1;
for (let i = 1; i < length; i++) {
const temp = input.filter(x => {
return x.type === ty;
})
if (temp.length < 2) {
this.result.push(`Type ${ty}: ${temp[0].color}`);
} else {
this.result.push(`Type ${ty}: ${temp[0].color}, ${temp[1].color}`);
}
this.ty = i + 1;
}
console.log('result', this.result);
// output
/* const output = [
"Type 1: Red(268), Blue(583)",
"Type 2: Blue(185)",
"Type 4: Red(326), Blue(967)",
"Type 5: Red(863)"
] */
解决方案
您可以使用Array.reduce()函数来迭代您的数组并构造一个新对象。
const input = [{
"type": 1,
"color": "Red(268)"
},
{
"type": 1,
"color": "Blue(583)"
},
{
"type": 2,
"color": "Blue(185)"
},
{
"type": 4,
"color": "Red(326)"
},
{
"type": 4,
"color": "Blue(967)"
},
{
"type": 5,
"color": "Red(863)"
}
];
const mappedInput = input.reduce((grouped, {
type,
color
}) => {
if (!grouped.hasOwnProperty(type)) {
grouped[type] = `Type ${type}: ${color}`;
} else {
grouped[type] += `, ${color}`;
}
return grouped;
}, {});
console.log(Object.values(mappedInput));
我们使用一个对象来提供有效的键查找,最后只检索我们需要的字符串数组。
推荐阅读
- java - 如何在 Java 中反序列化 JSON 对象数组
- django - id 不存在于 validate() 和 ListSerializer 的 update() Django Rest Framework
- python - 如何在机器人框架中执行特定的测试用例 n 次
- javascript - 如何使用 NodeJS 在 selenium-webdriver 中选择下拉值
- keras - 使用 Keras 的 ELMo 嵌入层中 variable_scope 的问题
- java - 来自数据库的具有字段、值和数据类型的动态 Java 对象
- vba - 在当前发送电子邮件中通过 Active Explorer 获取当前正文
- azure - 需要通过 REST API 了解 Azure 中的运行命令
- javascript - 开玩笑 - 如果调用了多个函数,如何使用期望一次来断言
- ios - 在不使用 alpha 的情况下使用 UISegmentedControl 在视图 ios 之间切换?