javascript 基于变量javascript对数组项进行分组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7596794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:39:05  来源:igfitidea点击:

Group array items based on variable javascript

javascriptjqueryarraysmultidimensional-arraygrouping

提问by Tobias

I have an array that is created dynamic from an xml document looking something like this:

我有一个从 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]

This array is created within a for loop and could contain whatever based on the xml document

这个数组是在 for 循环中创建的,可以包含基于 xml 文档的任何内容

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

我需要完成的是根据字母对该数组中的项目进行分组,以便所有包含字母 A 的数组对象都存储在另一个数组中,如下所示

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

为了澄清,我需要根据数组中的变量对项目进行排序,在这种情况下是字母,以便包含字母 A 的所有数组对象都在新数组下一个字母

Thanks for any help!

谢谢你的帮助!

采纳答案by nnnnnn

You shouldn't use arrays with non-integer indexes. Your othervariable should be a plain object rather than an array. (It does work with arrays, but it's not the best option.)

您不应该使用具有非整数索引的数组。您的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]);
}

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 otheror 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.

给定myArray[1,"The Melting Pot","A"] 中的一个项目,您的示例并未说明您是要将整个内容存储other在第二个数组位置中还是仅存储在第二个数组位置的字符串字段中 - 您的示例仅输出有字符串,但它们与您在myArray. 我的代码最初只存储了字符串部分other[letter].push(myArray[i][1]);,但是一些匿名的人已经编辑了我的帖子,将其更改为other[letter].push(myArray[i]);存储所有 [1,"The Melting Pot","A"] 的内容。由你决定你想在那里做什么,我已经给了你你需要的基本代码。

回答by slv007

Try groupBy function offered by http://underscorejs.org/#groupBy

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

回答by Jose Faeti

You have to create an empty JavaScript object and assign an array to it for each letter.

您必须创建一个空的 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] ];
}

Demo fiddle here.

演示小提琴在这里

回答by kzh

Good ol' ES5 Array Extras are great.

Good ol' ES5 Array Extras 很棒。

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

回答by user278064

This codewill work for your example.

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

回答by Jayendra

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

}