【问题标题】:Group array items based on variable javascript基于变量 javascript 对数组项进行分组
【发布时间】:2011-11-27 15:34:17
【问题描述】:

我有一个从 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 的数组对象按字母排列在新数组下

感谢您的帮助!

【问题讨论】:

    标签: javascript jquery arrays multidimensional-array grouping


    【解决方案1】:

    此代码适用于您的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);
    }
    

    【讨论】:

      【解决方案2】:

      您不应该使用具有非整数索引的数组。你的 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,“The Melting Pot”,“A”]。由你来决定你想在那里做什么,我已经给你你需要的基本代码。

      【讨论】:

      • 我编辑了您的答案,以说明缺少括号并将整个数组添加到对象中,而不仅仅是标题。这是您的demo。我希望你不要介意。 :)
      • @nnnnnn “某个匿名人士编辑了我的帖子” 哈哈。我留下了一条评论,除了 SO 自动记录编辑历史之外,对我来说,这看起来不像是匿名的。 :D
      • @Shef - 抱歉,是的,我现在看到了您的评论(包括您的 cmets),但当时我写道,SO 拒绝向我展示编辑历史,我认为这一定是因为您在没有保留历史记录的初始宽限期内进行了编辑。具有讽刺意味的是,当您进行更改时,我正在自己编辑它,特别指出我只存储了标题部分并询问实际要求是什么。所以弹出了一个关于你的编辑的警告,但由于某种原因不会告诉我细节。
      • P.S.感谢@Shef 的演示。
      【解决方案3】:

      试试 -

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

      【讨论】:

        【解决方案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] ];
        }
        

        演示小提琴here.

        【讨论】:

          【解决方案5】:

          Good ol' ES5 Array Extras 很棒。

          var other = {};
          myArray.forEach(function(n, i, ary){
              other[n[2]] = n.slice(0,2);
          });
          

          【讨论】:

            【解决方案6】:

            试试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]}
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2014-04-01
              • 1970-01-01
              • 2021-11-18
              • 2017-03-09
              • 1970-01-01
              相关资源
              最近更新 更多