基于JavaScript的变量数组组项目 [英] Group array items based on variable javascript
问题描述
我有创建从XML文档动态看起来像这样的数组:
I have an array that is created dynamic from an xml document looking something like this:
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]
这阵内创建循环,并可能包含任何基于XML文档
This array is created within a for loop and could contain whatever based on the xml document
我需要做到的是分组从这个阵列基于字母的项目是什么让那些在他们的字母A的所有数组对象获取存储在另一个数组,因为这
What I need to accomplish is grouping the items from this array based on the letters so that all array objects that have the letter A in them get stored in another array as this
other['A'] = ['item 1', 'item 2', 'item 3'];
other['B'] = ['item 4', 'item 5'];
other['C'] = ['item 6'];
要澄清,我需要根据变量项目从阵列中梳理,在这种情况下,字母,使包含字母A的所有数组对象而来的新数组下通过信函
To clarify I need to sort out items based on variables from within the array, in this case the letters so that all array objects containing the letter A goes under the new array by letter
任何帮助的感谢!
推荐答案
您不应该使用非整数的索引数组。你的等
变量应该是一个普通的对象,而不是一个数组。 (它使用数组,但它不是最好的选择。)
You shouldn't use arrays with non-integer indexes. Your other
variable should be a plain object rather than an array. (It does work with arrays, but it's not the best option.)
// 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,大熔炉,A],你的例子并不清楚你是否要存储整在事等
或只是在第二阵列位置的字符串字段 - 您的例子输出只有字符串,但是他们没有在 myArray的<匹配字符串/ code>。我的code最初说
其他[信] .push(myarray的[I] [1])存储只是字符串的一部分;
,但一些匿名人士已经编辑了我发帖将其更改为其他[信] .push(myarray的[I]);
存储所有的[1,大熔炉,A。你来找出你想要做什么有,我给你基本的code你需要的。
Given an item in myArray
[1,"The Melting Pot","A"], your example doesn't make it clear whether you want to store that whole thing in other
or just the string field in the second array position - your example output only has strings but they don't match your strings in myArray
. My code originally stored just the string part by saying other[letter].push(myArray[i][1]);
, but some anonymous person has edited my post to change it to other[letter].push(myArray[i]);
which stores all of [1,"The Melting Pot","A"]. Up to you to figure out what you want to do there, I've given you the basic code you need.
这篇关于基于JavaScript的变量数组组项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!