javascript - 从单个数组中获取不同的数组
问题描述
我有以下输入数组,
var temp = ['3_2', '3_2', '3_2', '4_2', '4_2', '5_2', '5_2' ]
那,我需要分成如下的临时数组,
var temp1 = ['3_2', '3_2', '3_2']
var temp2 = ['4_2', '4_2']
var temp3 = ['5_2', '5_2']
解决方案
您可以使用Object.values()
和.reduce()
:
var temp = ['3_2', '3_2', '3_2', '4_2', '4_2', '5_2', '5_2' ];
var result = Object.values(temp.reduce((a, c) => {
let [v] = c.split('_');
a[v] = a[v] || [];
a[v].push(c);
return a;
}, {}));
var [temp1, temp2, temp3] = result;
console.log(temp1);
console.log(temp2);
console.log(temp3);
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- machine-learning - 您如何区分与神经网络中的权重相关的误差?
- ios - 从 API 传递的图像未在页面浏览容器中快速显示
- c++ - 构造函数中的weak_from_this()
- javascript - Issue with storing and recalling cookies Javascript
- react-native - onPress 功能不起作用
- sql-server - 如何从本地实例查询/插入 - Azure SQL Server
- java - Spring Boot login error
- csv - NullPointerException while load csv using neo4j's apoc.periodic.iterate procedure
- vb.net - 保存 Word 文档导致“命令失败”
- c# - Using JsonConvert.DeserializeObject on JSON with dynamic object name