我有两个相等长度的数组。
array1 = {a,a,a,b,b,b,b,b,c,c,c,c,c,c,d,d,d,d,e,e} array2 = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20} i want to create an object. var obj = { 'a': {1,2,3} 'b': {4,5,6,7,8} 'c': {9,10,11,12,13,14} ..... ..... }
有人可以帮助我解决逻辑。
答案 0 :(得分:4)
假设你的意思是你的例子中的数组(名称+问题标题):
var combined = {};
for(var i = 0; i < array1.length; i++) {
var key = array1[i];
if(!(key in combined)) {
combined[key] = [];
}
combined[key].push(array2[i]);
}
答案 1 :(得分:3)
var group = {};
if (array1.length == array2.length) {
for (var i=0, j=array1.length; i<j; i++) {
if ( !(array1[i] in group) ) group[array1[i]] = [];
group[array1[i]].push(array2[i]);
}
}
答案 2 :(得分:2)
var array1 = ['a','a','a','b','b','b','b','b','c','c','c','c','c','c','d','d','d','d','e','e'];
var array2 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
var obj = {};
for (var i = 0, key; (key = array1[i]); i++) {
if (!obj[key]) {
obj[key] = [];
}
obj[key].push(array2[i]);
}
应该做的伎俩。
答案 3 :(得分:0)
var array1 = ['a','a','a','b','b','b','b','b','c','c','c','c','c','c','d','d','d','d','e','e']
var array2 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
var travesedArrayIndex=[];
var Component=function(name, count)
{
this.name=name;
this.number=count;
}
var componentList=[];
for(i=0;i<array1.length; i++)
{
var count=0;
var valueToBeComparedWith=array1[i];
for(j=0;j<array1.length;j++)
{
if(!AlreadyTraversed(j))
{
if(valueToBeComparedWith==array1[j])
{
count=count+1;
travesedArrayIndex.push(j);
}
}
}
if(count>0)
{
var comp= new Component(valueToBeComparedWith,count);
componentList.push(comp);
}
}
var FinalComponent=function()
{
this.item;
this.numberArray=[];
}
var FinalComponentList=[];
var j=0;
for(i=0;i<componentList.length;i++)
{
var finalComp= new FinalComponent();
finalComp.item=componentList[i].name;
var sizeOfArray=componentList[i].number + j;
for(j;j<sizeOfArray;j++)
{
finalComp.numberArray.push(array2[j]);
}
FinalComponentList.push(finalComp);
}
console.log(FinalComponentList);
function AlreadyTraversed(index)
{
for(k=0;k<travesedArrayIndex.length;k++)
{
if(index==travesedArrayIndex[k])
{
return true;
}
}
return false;
}