3

I mostly develop in Java, but I presently need to do some work using JavaScript.

I have data that I need to group by two dimensions: first by gender, and then by language. The object to be grouped comes like so:

var items =[ {
  "language":"english",
  "gender":"male",
  ...//twelve other fields
},
...
]

This is what I've tried:

var myMap = {};
for(var i=0; i<items.length;i++){
  var item = items[i];
  var _gender = item["gender"];
  var _lang = item["language"];
  myMap[_gender][_lang].push[item];
}

I assumed the above would work, but it’s not working. It keeps returning this error:

Uncaught TypeError: Cannot read property 'undefined' of undefined

Note: In Java, I would be creating a map of arrays.

Katedral Pillon
  • 14,534
  • 25
  • 99
  • 199

2 Answers2

0

You are doing totally wrong. First of all myMap is object not an array so you can not use myMap.push(). You can achieve like this.

var items = {
  "language":"english",
  "gender":"male"
}
var myMap = {};
for(var key in items){
   var myArray = [];
   var _gender = items["gender"];
   var _lang = items["language"];
   myArray.push(_gender);
   myArray.push(_lang);
   myMap.item = myArray;
   console.log(myMap);
}

for add 2-d array read this. 2-D Array in javascript

Community
  • 1
  • 1
Durgpal Singh
  • 11,481
  • 4
  • 37
  • 49
  • Thanks for replying. I am going to test. But by just looking, yours looks like an array of maps whereas what I need is a map of arrays. I.e. a map where each key has for value an array of items. – Katedral Pillon Dec 24 '16 at 06:20
0

One problem:

When you call myMap[_gender][_lang].push[item];, what you are actually doing is adding a key to the Object myMap, with the current value of _gender, and turning it into an Object, which you then create a new key for, set to the value of _lang. In addition, .push() is a function used with arrays, to add a new item onto the end of the array. If you want to add a new key and value to an Object, all you have to do is just call that key and assign it a value. Here's an example.

var obj = {
  ex1 : 'example 1',
  ex2 : 'example 2'
};

console.log(obj);

obj.ex3 = 'example 3';

console.log(obj);

//The code below will simply log 'undefined' in most consoles(it doesn't happen to do so in this snippet).
console.log(obj.ex4);

Here's my suggestion(assuming I correctly understand what you're trying to do):

var items = [{
  "language":"english",
  "gender":"male",
},
//...more below
];

myMap = [];


for(var i = 0; i < items.length; i++){
  myArray = [];
  var item = items[i];
  var _gender = item["gender"];
  var _lang = item["language"];
  myArray.push(_gender);
  myArray.push(_lang);
  myMap.push(myArray);
}
TrojanByAccident
  • 227
  • 1
  • 6
  • 20