特定组合的jQuery的数组串联除非复制 [英] jquery array concatenation of specific combinations except where duplicate

查看:118
本文介绍了特定组合的jQuery的数组串联除非复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种方式数据:

[Array1] = ['blue','green', 'yellow','red','very very red']
[Array2] = ['ColumnA','ColumnB','ColumnC','ColumnD','ColumnD']

这导致两行。所需的JSON输出:

This results in two rows. Desired JSON output:

{ 'row1': {'ColumnA':'blue','ColumnB':'green','ColumnC':'yellow','ColumnD':'red'}
  'row2': {'ColumnA':'blue','ColumnB':'green',,'ColumnC':'yellow','ColumnD':'very very red'}
}

注意,数组1和ARRAY2都对。 ColumnD有两种情况。

Notice that Array1 and Array2 are pairs. ColumnD has two cases.

美中不足的是,ARRAY2可以有任意数量的重复(例如使用ColumnA另一种情况)。

The catch is that Array2 can have any number of duplicates (for example another case with ColumnA).

循环和建筑指数表的前景保持循环轨道的数量是一个可怕的前景。

The number of loops and prospect of building index tables to keep track of the loops is a daunting prospect.

我在寻找咨询如何做到这一点。我知道SQL会是一个更好的节目选择,但我调查一个jQuery功能。

I'm looking for advice on how to do this. I know sql would be a better programming choice, but I'm investigating a Jquery function.

推荐答案

编辑:工作溶液;)

问题是,我居然冲进了错误的方向。我想出了以下的想法,它使用一个递归函数,因此使得它更容易阅读。

The thing is, I actually rushed into the wrong direction. I came up with the following idea, which uses a recursive function therefore making it much more easy to read.

实际上,要具备所有的组合,没有排列。在这里,我只放一个彩色的第一个字母。所以,从

Indeed, you want to have all the combinations, without the permutations. Here I put only the first letter of a color. So, from:

b1 b2 g1 y1 y2 r1 r2 r3
A  A  B  C  C  D  D  D

您想拥有(这里的顺序是什么code会做):

You want to have (the order here is what the code will do):

A  B  C  D
b1 g1 y1 r1
b1 g1 y1 r2
b1 g1 y1 r3
b1 g1 y2 r1
b1 g1 y2 r2
b1 g1 y2 r3
b2 g1 y1 r1
b2 g1 y1 r2
b2 g1 y1 r3
b2 g1 y2 r1
b2 g1 y2 r2
b2 g1 y2 r3

首先,我想为列/彩色阵列另一种格式,因为它会更容易的工作。我想从

First, I wanted another format for the column/color array, as it would be easier to work with. I wanted to go from

[b1,b2,g1,y1,y2,r1,r2,r3]
[A ,A ,B ,C ,C ,D ,D ,D]

[[b1,b2],[g1],[y1,y2],[r1,r2,r3]]
[   A   , B  ,   C   ,    D     ]

此方式,我们将有,对于每一列的值,匹配子阵列containg所有颜色相关的列

This way we would have, for each column value, a matching subarray containg all the colors related to the column.

下面的函数达到此目的(尽管它可能是不这样做的最佳方式):

The following function achieves this purpose (even though it is probably not the optimal way to do it):

//column and color are the paired arrays you have as data input
function arrangeArrays(column, color) {
  var ret=new Array(); //the returned container for the data
  ret["color"]=new Array(); //the color part of the returned data
  ret["column"]=new Array(); //the column part of the returned data
  var tmp=new Array(); //an internal array we'll use to switch from associative keys to normal keys
  //we parse the paired arrays
  for(var i in column) {
    //if the column is not an associative key in tmp, we declare it as an array
    if(!tmp[column[i]])
      tmp[column[i]]=new Array();
    //we add the color to the subarray matching its column
    tmp[column[i]].push(color[i]);
  }
  //now we just translate these horrible associative keys into cute array-standard integer keys
  for(var i in tmp) {
    ret["color"].push(tmp[i]);
    ret["column"].push(i);
  }
  //the commented code is a quick does-it-work block
  /*
  for(var i in ret["column"]) {
    document.write("column="+ret["column"][i]+" --- color(s)="+ret["color"][i].join()+"<br>");
  }
  */
  return ret;
}

现在的核心。该函数调用每一个将处理一列,实际上只是它的一部分,使用递归处理等栏目。用一个简单的例子中,code做到这一点:

Now to the core. Each call to the function will process one column, and actually only a part of it, using recursion to deal with other columns. Using a simplified example, the code does this:

[[b1,b2],[y1,y2]]
[   A   ,   B   ]
total combinations: 2*2=4

first call for 1st column, length is 4, 2 possible values, first insert loops 4/2=2 times:
b1
b1
call for 2nd column, length is 2, 2 possible values, first insert loops 2/2=1 time:
b1 y1
b1
call for 3rd column, no 3rd column, coming back
call for 2nd column, length is 2, 2 possible values, second insert loops 2/2=1 time:
b1 y1
b1 y2
call for 3rd column, no 3rd column, coming back
call for 2nd column done, coming back
first call for 1st column, length is 4, 2 possible values, second insert loops 4/2=2 times:
b1 y1
b1 y2
b2
b2
call for 2nd column, length is 2, 2 possible values, first insert loops 2/2=1 time:
b1 y1
b1 y2
b2 y1
b2
call for 3rd column, no 3rd column, coming back
call for 2nd column, length is 2, 2 possible values, second insert loops 2/2=1 time:
b1 y1
b1 y2
b2 y1
b2 y2
call for 3rd column, no 3rd column, coming back
call for 2nd column done, coming back
call for 1st column done, coming back (returning)

下面是code,帮助自己阅读的意见;)

Here is the code, help yourself reading the comments ;)

//results is an empty array, it is used internally to pass the processed data through recursive calls
//column and color would be the subarrays indexed by "column" and "color" from the data received by arrangeArrays()
//resultIndex is zero, it is used for recursive calls, to know where we start inserting data in results
//length is the total of results expected; in our example, we have 2 blues, 1 green, 2 yellows, and 3 reds: the total number of combinations will be 2*1*2*3, it's 12
//resourceIndex is zero, used for recursive calls, to know what column we are to insert in results
function go(results, column, color, resultIndex, length, resourceIndex) {
  //this case stops the recursion, it means the current call tries to exceed the length of the resource arrays; so we just return the data without touching it
  if(resourceIndex>=column.length)
    return results;
  //we loop on every color mentioned in a column
  for(var i=0;i<color[resourceIndex].length;i++) {
    //so for every color, we now insert it as many times as needed, which is the length parameter divided by the possible values for this column
    for(var j=0;j<length/color[resourceIndex].length;j++) {
      //ci will be the index of the final array
      //it has an offset due to recursion (resultIndex)
      //each step is represented by j
      //we have to jump "packs" of steps because of the loop containing this one, which is represented by i*(the maximum j can reach)
      var ci=resultIndex+i*(length/color[resourceIndex].length)+j;
      //the first time we use ci, we have to declare results[ci] as an array
      if(!results[ci])
        results[ci]=new Array();
      //this is it, we insert the color into its matching column, and this in all the indexes specified through the length parameter
      results[ci][column[resourceIndex]]=color[resourceIndex][i];
    } //end of j-loop
    //we call recursion now for the columns after this one and on the indexes of results we started to build
    results=go(results, column, color, resultIndex+i*(length/color[resourceIndex].length), length/color[resourceIndex].length, resourceIndex+1);
  } //end of i-loop
  //we now pass the data back to the previous call (or the script if it was the first call)
  return results;
}

我测试使用code的此位(如果你想体验的每一步会发生什么可能是有用的)功能:

I tested the function using this bit of code (might be useful if you want to experience what happens on each step):

function parseResults(res) {
  for(x in res) { //x is an index of the array (integer)
    for(var y in res[x]) { //y is a column name
      document.write(x+" : "+y+" = "+res[x][y]); //res[x][y] is a color
      document.write("<br>");
    }
    document.write("<br>");
  }
}

您会恐怕还需要一个函数来告诉去()用什么长度的第一个电话。像这样的:

You'll probably also need a function to tell go() what length to use for the first call. Like this one:

function getLength(color) {
  var r=1;
  for(var i in color)
    r*=color[i].length;
  return r;
}

现在,假设你有一个数组和阵列颜色

Now, assuming you have an array column and an array color:

var arrangedArrays=arrangeArrays(column, color);
var res=go(new Array(), arrangedArrays["column"], arrangedArrays["color"], 0, getLength(arrangedArrays["color"]), 0);

这似乎很大,但我想解释一下好了,反正如果您删除在code和注释的例子,它不是那么大......整个事情是几乎不会疯了这些指标;)

Here it is, seems big but I wanted to explain well, and anyway if you remove the comments in the code and the examples, it's not that big... The whole thing is just about not going crazy with these indexes ;)

下面这是第一个答案,它没有很好地工作......这,好了,没有工作。

This below was the first answer, which didn't work well... which, well, didn't work.

您可以使用关联数组(或评估对象/属性的语法,这是大致相同)。这样的事情:

You can use "associative arrays" (or eval an object/property-like syntax, it's about the same). Something like that:

var arrayResult=new Array();
var resultLength=0;
for(var globalCounter=0;globalCounter<arrayColumn.length;globalCounter++) {
  //if this subarray hasn't been init'd yet, we do it first
  if(!arrayResult[resultLength])
    arrayResult[resultLength]=new Array();
  //case: we already inserted a color for the current column name
  if(arrayResult[resultLength][arrayColumn[globalCounter]]) {
    //1: we copy the current subarray of arrayResult to a new one
    resultLength++;
    arrayResult[resultLength]=new Array();
    for(var i=0;i<=globalCounter;i++)
      arrayResult[resultLength][arrayColumn[i]]=arrayResult[resultLength-1][arrayColumn[i]];
    //2: we replace the value for the conflicting colmun
    arrayResult[resultLength][arrayColumn[globalCounter]]=arrayColor[globalCounter];
  //case: default, the column wasn't already inserted
  } else {
    //we simply add the column to each subarray of arrayResult
    for(var i=0;i<=resultLength;i++)
      arrayResult[i][arrayColumn[globalCounter]]=arrayColor[globalCounter];
  }
}

从那里,我想这是很容易把它翻译成JSON格式。

From there, I suppose it's easy to translate it to JSON format.

当您解析子阵列,请记住,关联键实际上是方法,即你不能与循环(X = 0; X&LT; array.length ; X ++),而是使用为(以数组x);你必须测试的关键,并确保其与处理前栏开始(或者你会最终处理对长度/ 0 ^^)。同样在arrayResult的钥匙,如果你想这个容器数组有那样的钥匙。

When you parse the subarrays, keep in mind that associative keys are actually methods, i.e. you can't loop with for(x=0;x<array.length;x++), instead use for(x in array) ; and you have to test the key and be sure it starts with "column" before processing it (or you'll end processing the pair "length"/0 ^^). Same on arrayResult's keys if you want this container array to have that kind of keys.

最后一件事:我没有测试code,它可能会错过了一下,还是可能会有一些错误输入。其目的是为了帮助,不要做:)

One last thing: I didn't test the code, it may miss a bit, or there may be some mistyping. The purpose is to help, not to do :)

祝你好运!

这篇关于特定组合的jQuery的数组串联除非复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆