开发者

array problem in javascript : Logic

开发者 https://www.devze.com 2023-03-21 17:37 出处:网络
i have this two arrays of equal len开发者_Go百科gth. array1 = {a,a,a,b,b,b,b,b,c,c,c,c,c,c,d,d,d,d,e,e}

i have this two arrays of equal len开发者_Go百科gth.

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}
 .....
 .....
}

can somebody help me with the logic.


Assuming you mean arrays in your example (names + question title):

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]);
}


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]);
  }
}


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]);
}

Should do the trick.


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消