Jeanbf
Jeanbf

Reputation: 317

How can I create an new array for each specific data in a loop in javascript?

I have this function:

flotLinea:function(tareas){

var self = this;
console.info(tareas);
     var aTar = new Array();

        for(var i = 0;i<tareas.length;i++){

          var val = new Array(new Date(tareas[i].fecha_registro),tareas[i].porcentaje);
                aTar.push(val);
        }

    console.info(aTar);

},

Using console.info(tareas); print this :

enter image description here

And using console.info(aTar); print :

enter image description here

(The data from tareas always is changing because the data comes from a dropdown)

I need create an new array for each id_usu using the same data , how can I do this?

For example in this case I need an array for id_usu = 4 ( are two id_usu = 4, so i need the data where id_usu = 4) , one array with id_usu = 6 and one array with id_usu = 9

I need do this , because this data are for a chart, so, after , each user ( id_usu ) will be a different color in that chart.

Upvotes: 0

Views: 120

Answers (1)

Sudhansu Choudhary
Sudhansu Choudhary

Reputation: 3360

From whatever I have understood form your problem statement and the code you have provided, I've provided a solution below.

flotLinea:function(tareas){

    var self = this;
    console.info(tareas);
     var aTar = new Array();
     var idArray = [];

        for(var i = 0;i<tareas.length;i++){
            if(idArray.indexOf(tareas[i].id_usu) == -1){
              var val = new Array(new Date(tareas[i].fecha_registro),
                  tareas[i].porcentaje);
                idArray.push(tareas[i].id_usu);
                aTar.push(val);
               }
             else{
                   for(var j = 0; j < aTar.length; j++){
                        if(tareas[i].id_usu == aTar[j][0].id_usu){
                           aTar[j].length = new Array(new Date(tareas[i].fecha_registro)
                      ,tareas[i].porcentaje);     
                         }
                     }
                 }
        }

    console.info(aTar);

}

I'm using Brute-Force kind of solution, performance can always be increased.

I've created on new array above as idArray to hold the unique id_usus, and am comparing if the current tareas[i].id_usu already is there in that array, if not push the new value to aTar array and tareas[i].id_usu to idArray, else loop over the aTar array and find the array which already has the object with the current tareas[i].id_usu and push the new values at aTar[j].length.

Upvotes: 1

Related Questions