Group array items based on variable javascript

前端 未结 6 1467
囚心锁ツ
囚心锁ツ 2020-12-31 11:18

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 Mexican         


        
6条回答
  •  再見小時候
    2020-12-31 12:11

    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]);
    }
    

    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.

提交回复
热议问题