基于变量javascript对数组项进行分组

时间:2011-09-29 11:42:28

标签: javascript jquery arrays multidimensional-array grouping

我有一个从xml文档动态创建的数组,如下所示:

myArray[0] = [1,The Melting Pot,A]
myArray[1] = [5,Mama's MexicanKitchen,C]
myArray[2] = [6,Wingdome,D]
myArray[3] = [7,Piroshky Piroshky,D]
myArray[4] = [4,Crab Pot,F]
myArray[5] = [2,Ipanema Grill,G]
myArray[6] = [0,Pan Africa Market,Z]

此数组是在for循环中创建的,可以包含基于xml文档的任何内容

我需要完成的是根据字母对此数组中的项进行分组,以便所有包含字母A的数组对象都存储在另一个数组中

other['A'] = ['item 1', 'item 2', 'item 3'];
other['B'] = ['item 4', 'item 5'];
other['C'] = ['item 6'];

澄清我需要根据数组中的变量对项目进行排序,在本例中为字母,以便所有包含字母A的数组对象都按字母排在新数组下

感谢您的帮助!

6 个答案:

答案 0 :(得分:10)

您不应该使用具有非整数索引的数组。您的other变量应该是普通对象而不是数组。 (它确实适用于数组,但它不是最佳选择。)

// assume myArray is already declared and populated as per the question

var other = {},
    letter,
    i;

for (i=0; i < myArray.length; i++) {
   letter = myArray[i][2];
   // if other doesn't already have a property for the current letter
   // create it and assign it to a new empty array
   if (!(letter in other))
      other[letter] = [];

   other[letter].push(myArray[i]);
}

鉴于myArray [1,“The Melting Pot”,“A”]中的一个项目,您的示例并不清楚您是否要将整个内容存储在other中或只是第二个数组位置中的字符串字段 - 您的示例输出仅包含字符串,但它们与myArray中的字符串不匹配。我的代码最初只是通过说other[letter].push(myArray[i][1]);来存储字符串部分,但是一些匿名人员编辑了我的帖子以将其更改为other[letter].push(myArray[i]);,其中存储了所有[1,“The Melting Pot”,“A”] 。由你决定你想做什么,我已经给你了你需要的基本代码。

答案 1 :(得分:6)

尝试http://underscorejs.org/#groupBy

提供的groupBy功能
_.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });

Result => {1: [1.3], 2: [2.1, 2.4]}

答案 2 :(得分:2)

您必须创建一个空的JavaScript对象,并为每个字母分配一个数组。

var object = {};

for ( var x = 0; x < myArray.length; x++ )
{
    var letter = myArray[x][2];

    // create array for this letter if it doesn't exist
    if ( ! object[letter] )
    {
        object[letter] = [];
    }

    object[ myArray[x][2] ].push[ myArray[x] ];
}

演示小提琴here

答案 3 :(得分:1)

代码适用于您的example

var other = Object.create(null),  // you can safely use in opeator.
    letter,
    item,
    max,
    i;

for (i = 0, max = myArray.length; i < max; i += 1) {
   item = myArray[i];
   letter = myArray[2];

   // If the letter does not exist in the other dict,
   // create its items list
   other[letter] = other[letter] || [];
   other.push(item);
}

答案 4 :(得分:1)

Good ol'ES5 Array Extras很棒。

var other = {};
myArray.forEach(function(n, i, ary){
    other[n[2]] = n.slice(0,2);
});

答案 5 :(得分:0)

尝试 -

var myArray = new Array();
myArray[0] = [1,"The Melting Pot,A,3,Sake House","B"];
myArray[1] = [5,"Mama's MexicanKitchen","C"];
myArray[2] = [6,"Wingdome","D"];
myArray[3] = [7,"Piroshky Piroshky","D"];
myArray[4] = [4,"Crab Pot","F"];
myArray[5] = [2,"Ipanema Grill","G"];
myArray[6] = [0,"Pan Africa Market","Z"];

var map = new Object();
for(i =0 ; i < myArray.length; i++){
    var key = myArray[i][2];
    if(!map[key]){
       var array = new Array();        
        map[key] = array;
    }
    map[key].push(myArray[i]);

}
相关问题