基于变量将数组项分组 Javascript

11

我有一个动态生成的数组,从一个类似于这样的 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个回答

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”]。由您决定要在那里执行什么操作,我已经提供了您所需的基本代码。

我修改了你的答案,加上了一个缺失的括号,并将整个数组添加到对象中,而不仅仅是标题。这是你的demo。希望你不介意。 :) - Shef
2
@nnnnnn “有个匿名人编辑了我的帖子” 哈哈。除了SO自动记录编辑历史之外,我留下了评论,对我来说看起来并不像是匿名的。 :D - Shef
@Shef - 抱歉,是的,我现在看到了你的评论(两个评论),但当时我写下这句话时,SO拒绝显示编辑历史记录,我以为这是因为你在初始宽限期内进行了编辑,因此没有保留历史记录。具有讽刺意味的是,当你的更改完成时,我正在编辑它,特别是要指出我只存储了标题部分,并询问实际要求是什么。SO弹出了一个关于你的编辑的警告,但出于某种原因不会告诉我详细信息。 - nnnnnn
P.S. 谢谢 @Shef 提供的演示。 - nnnnnn

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
你需要创建一个空的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] ];
}

演示fiddle 这里


1

这个代码适用于你的例子

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

1

好老的 ES5 数组扩展非常棒。

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

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

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接