0

I have two arrays

A =[1990,1991,....]
B=[a,b,c,d,e,f,...]

I want the resultant array in this format

Resultant=[{
                name: 1990,
                data: [a,b,c]

            },{
                name: 1991,
                data: [d,e,f]

            },...
           ]

Please help me how will I make it using for loops?

4 Answers4

0

This will format data with Array.prototype.map, based on your (rather vague) requirement:

var A = [1990,1991];
var B = ["a","b","c","d","e","f"];

var formatted = A.map(function (name, i) {
    return {
        name: name,
        data: B.slice(i*3, i*3+3)
    }
});

/*[
    {
        "name": 1990,
        "data": [
            "a",
            "b",
            "c"
        ]
    },
    {
        "name": 1991,
        "data": [
            "d",
            "e",
            "f"
        ]
    }
]*/
0

Assuming that for each in A, you want data to store 3 elements of B. I've stuck with your requirement of using for loops.

var Resultant = [];
for (var i = 0; i < a.length; i++) {
   var data = [];
   for (var j = 0; j < 3, B.length > 0; j++) {
       data.push(B.shift());
   }

   Resultant.push({name: A[i], 'data': data});
}
NRaf
  • 7,407
  • 13
  • 52
  • 91
0

How about this:

var b= ["a","b","c","d","e","f"];
var result = [1990,1991].map(function(n){ return { name:n, data: b.splice(0,3)} });
Dalorzo
  • 19,834
  • 7
  • 55
  • 102
  • This is working but data value are not getting correctly it is getting 0 values. –  Feb 07 '14 at 05:23
  • It is partially working thank you for the logic. But in data the values are not correctly getting. can you rectify it? –  Feb 07 '14 at 05:30
  • data is an array it is returning an array I think we all did it that way – Dalorzo Feb 07 '14 at 05:31
  • Image added please help me. –  Feb 07 '14 at 05:38
  • In highcharts x axis is coming but y axis is not showing, its getting zero values –  Feb 07 '14 at 08:47
0

This worked for me:

http://jsfiddle.net/s5zdD/ <-- see jsfiddle to show

A =[1990,1991,1992];
B=['a','b','c','d','e','f','g','h','i'];

var Resultant = jQuery.map(A, function(i,v){
// if no jQuery use:
// var Resultant = A.map(function(i,v){
    return {
        'name':A[v],
        'data': B.splice(0,3)
    }
})

console.log(Resultant);
james emanon
  • 11,185
  • 11
  • 56
  • 97