我有一个从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,"熔炉","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]}
您必须创建一个空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] ];
}
此代码将适用于您的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);
}
Good ol' ES5 Array .
var other = {};
myArray.forEach(function(n, i, ary){
other[n[2]] = n.slice(0,2);
});
Try -
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]);
}