首页 > 解决方案 > 从单个数组中获取不同的数组

问题描述

我有以下输入数组,

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']

标签: javascriptarraystypescript

解决方案


您可以使用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; }


推荐阅读