convert array to Map in javascript

1

I want to convert an array to Map (), in this console "console.log (arrayParaMap);" sale undefined the example I use is this // example {a: 1, a: 2, a: 1, b: 1, b: 5, b: 6} the map I intend to obtain is [a, {1,2,1}                                                b, {1,5,6}]

this is my code Code

var revisados=[];
var mapita=new Map();
var fabrica =function(array){ //input array -  output map
    for (var i = 0; i < array.length; i++) {
        var arreglo1=array[i].split(":");
        var arrayParaMap=[];
        for (var j = 0; j < array.length; j++) {
            var arreglo2=array[j].split(":");
            if(!db(arreglo1[0])){
                if(arreglo1[0]==arreglo2[0]){
                    arrayParaMap.push(arreglo2[2]);
                    console.log(arrayParaMap);
                }   
            }

        };
        mapita.set(arreglo1[0],arrayParaMap);
        revisados.push(arreglo1[0]);
    };
    for (var key of mapita.keys()) {
        console.log(key);
    }
    for (var value of mapita.values()) {
        // for (var i = 0; i < value.length; i++) {
            console.log(value);
        // };

    }
} 
var db=function(data){
    for (var i = 0; i < revisados.length; i++) {
        if(revisados[i]==data){
            return true;
        }
    };
return false;
}

//example {a:1,a:2,a:1,b:1,b:5,b:6}
var arregloPrueba=["a:1","a:2","a:1","b:1","b:5","b:6"];
fabrica(arregloPrueba);

Where am I failing?

    
asked by hubman 17.09.2016 в 03:10
source

1 answer

3

Maybe what you're looking for looks like this:

var arregloPrueba=["a:1","a:2","a:1","b:1","b:5","b:6"];

function matriz2mapa(matriz){
	var i,par;
	var mapa = new Map();
	for (i=0;i<matriz.length;i++){
		par = matriz[i].split(":");
		if (!mapa.has(par[0])) mapa.set(par[0],[]);
		mapa.get(par[0]).push(par[1]);
	}
	return mapa;
}
var mapa=matriz2mapa(arregloPrueba);
console.log("a:",mapa.get('a'));
console.log("b:",mapa.get('b'));
    
answered by 17.09.2016 / 04:44
source