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]
This array is created within a for loop and could contain whatever based on the xml document
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'];
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
Thanks for any help!
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.)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 inother
or just the string field in the second array position - your example output only has strings but they don't match your strings inmyArray
. My code originally stored just the string part by sayingother[letter].push(myArray[i][1]);
, but some anonymous person has edited my post to change it toother[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.Try groupBy function offered by http://underscorejs.org/#groupBy
Try -
This code will work for your
example
.You have to create an empty JavaScript object and assign an array to it for each letter.
Demo fiddle here.
Good ol' ES5 Array Extras are great.