I need to group element of a multidimensional array in javascript.
This is my array:
var data = [];
data.push(["ASIA", "CHINA", 1992, 31689222674, 5]);
data.push(["ASIA", "CHINA", 1997, 31327384072, 5]);
data.push(["ASIA", "INDIA", 1992, 27910388563, 5]);
data.push(["ASIA", "INDIA", 1993, 28669881069, 5]);
data.push(["ASIA", "INDIA", 1997, 29421629324, 5]);
data.push(["ASIA", "INDONESIA", 1992, 30990831267, 5]);
data.push(["ASIA", "INDONESIA", 1997, 31478506122, 5]);
data.push(["ASIA", "JAPAN", 1992, 29239959577, 5]);
data.push(["ASIA", "JAPAN", 1996, 29901316952, 5]);
data.push(["ASIA", "JAPAN", 1997, 29860665098, 5]);
data.push(["ASIA", "VIETNAM", 1992, 27229816811, 5]);
data.push(["ASIA", "VIETNAM", 1996, 27553006375, 5]);
data.push(["ASIA", "VIETNAM", 1997, 27240345298, 5]);
data.push(["AMERICA", "BRAZIL", 1992, 31689222674, 5]);
data.push(["AMERICA", "BRAZIL", 1993, 31207214888, 5]);
data.push(["AMERICA", "BRAZIL", 1994, 31926517793, 5]);
data.push(["AMERICA", "EUA", 1992, 27910388563, 5]);
data.push(["AMERICA", "EUA", 1993, 28669881069, 5]);
data.push(["AMERICA", "EUA", 1994, 29343326950, 5]);
I need to group elements by combining the contents of that array. I found this code, but it considers an array index.
function group(data, index) {
var o;
var other = {};
$.each(data, function(i, value) {
o = data[i][index];
if (!(o in other))
other[o] = [];
other[o].push(data[i]);
})
return other;
}
Then the group with more indices should be as an example: grouping by index 1 + 2.
ASIA - CHINA => ["ASIA", "CHINA", 1992, 31689222674, 5],
["ASIA", "CHINA", 1997, 31327384072, 5];
ASIA - INDIA => ....
ASIA - INDONESIA => .....
ASIA - JAPAN => ....
ASIA - VIETNAM =>
AMERICA - BRAZIL => ....
AMERICA - EUA => ....
This should also work for group involving more indices as well.
If you need this kind of functionality, underscore.js is highly recommended.
You could also customize the function
Demo