我有一个数组,它是从一个看起来像这样的 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 的数组对象都按字母放在新数组下
感谢您的帮助!
最佳答案
您不应该使用具有非整数索引的数组。您的 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"]。由您决定要在那里做什么,我已经为您提供了所需的基本代码。
关于javascript - 基于变量javascript对数组项进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7596794/