Tob*_*ias 11 javascript arrays jquery grouping multidimensional-array
我有一个从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]
Run Code Online (Sandbox Code Playgroud)
此数组是在for循环中创建的,可以包含基于xml文档的任何内容
我需要完成的是根据字母对此数组中的项进行分组,以便所有包含字母A的数组对象都存储在另一个数组中
other['A'] = ['item 1', 'item 2', 'item 3'];
other['B'] = ['item 4', 'item 5'];
other['C'] = ['item 6'];
Run Code Online (Sandbox Code Playgroud)
为了澄清我需要根据数组中的变量对项进行排序,在本例中为字母,以便包含字母A的所有数组对象都按字母顺序排列在新数组下
谢谢你的帮助!
nnn*_*nnn 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]);
}
Run Code Online (Sandbox Code Playgroud)
给定myArray[1,"The Melting Pot","A"]中的一个项目,你的例子不清楚你是想要存储整个东西other还是仅存储第二个数组位置的字符串字段 - 仅示例输出有字符串,但它们与你的字符串不匹配myArray.我的代码最初只是通过说法存储了字符串部分other[letter].push(myArray[i][1]);,但是一些匿名人员已经编辑了我的帖子以将其更改为other[letter].push(myArray[i]);存储所有[1,"The Melting Pot","A"].由您决定要在那里做什么,我已经为您提供了所需的基本代码.
尝试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]}
Run Code Online (Sandbox Code Playgroud)