我有下面的输入数组,
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']
答案 0 :(得分: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; }
答案 1 :(得分:0)
您可以使用带有变量引用的对象。
var temp = ['3_2', '3_2', '3_2', '4_2', '4_2', '5_2', '5_2'],
temp1 = [],
temp2 = [],
temp3 = [],
hash = { 3: temp1, 4: temp2, 5: temp3 };
temp.forEach(v => hash[v[0]].push(v));
console.log(temp1);
console.log(temp2);
console.log(temp3);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:0)
这是一个解决方案
const base = ['3_2', '3_2', '3_2', '4_2', '4_2', '5_2', '5_2'];
const newArrays = base.reduce((tmp, x) => {
const firstNumber = x.charAt(0);
// Look if there is an array about the first number
const index = tmp.findIndex(y => y[0].charAt(0) === firstNumber);
// If there is no array yet, add one
if (index === -1) {
tmp.push([
x,
]);
return tmp;
}
// Push in existing array
tmp[index].push(x);
return tmp;
}, []);
console.log(newArrays);
答案 3 :(得分:0)
使用Array.reduce()
迭代数组。如果不存在子数组或者当前项不适合当前子数组,则添加子数组。始终将项目推送到最后一个子阵列。获得temp_1/2/3
destructuring的结果:reduce:
const temp = ['3_2', '3_2', '3_2', '4_2', '4_2', '5_2', '5_2'];
const [temp_1, temp_2, temp_3] = temp.reduce((r, s) => {
const key = s.split('_')[0];
// if there isn't a sub array, or if the key doesn't fit the sub array, add a new sub array
if(!r[r.length - 1] || !r[r.length - 1][0].startsWith(key)) {
r.push([]);
}
// push to last subarry
r[r.length - 1].push(s);
return r;
}, []);
console.log('temp_1', temp_1);
console.log('temp_2', temp_2);
console.log('temp_3', temp_3);

答案 4 :(得分:0)
在提供的示例中,只有3个临时变量,但是,通常可以有许多变量,具体取决于测试用例。
您可以尝试以下
var temp = ['3_2', '3_2', '3_2', '4_2', '4_2', '5_2', '5_2' ];
var counter = 1;
var map = {};
temp.forEach(function(item){
if(map[item]) {
window["temp" + map[item]].push(item);
} else {
window["temp" + counter] = [item];
map[item] = counter++;
}
});
console.log(temp1);
console.log(temp2);
console.log(temp3);
此外,在上图中,我使用了window
,您也可以存储在object
中,然后将它们分配给变量
答案 5 :(得分:0)
按照我创建的代码。
var temp = ['3_2', '3_2', '3_2', '4_2', '4_2', '5_2', '5_2' ];
var j = 0;
this["temp"+j] = [];
for(var i=0; i<temp.length; i++)
{
var name = temp[i];
if($.inArray( name, this["temp"+j]) > -1)
{
this["temp"+j].push(name);
}
else
{
j++;
this["temp"+j] = [];
this["temp"+j].push(name);
}
}
console.log(temp1);
console.log(temp2);
console.log(temp3);