Merging two arrays non concatenative, from two seperate arrays, but with 1 common variable

Refresh

March 2019

Views

41 time

1

I'm trying to merge two arrays in a specific way, but cannot find the right syntax to do this.

primaryData = [1,2]
secondaryData = [3,4]
label = [label1, label2]

Currently this works

         data = $.map(labels, function(v, i) {

            return [[" " + v, " " + primaryData[i], " " + secondaryData[i]]] ;

        });

And gives me output of:

[["label1", "1"], ["label2", "2"]]

So two arrays in an array.

However I want this:

[["label1", "1"], ["label2", "2"], ["label1", "3"], ["label2", "4"]]

So basically doing the same thing twice with "labels" and then add numbers from two different sources.

I have tried this:

         data = $.map(labels, function(v, i) {

            return [[" " + v, " " + primaryData[i]], [" " + v, " " + secondaryData[i]]];

        });

But that provides me with:

[["label1", "1"], ["label1", "3"], ["label2", "2"], ["label2", "4"]]

So it seems like the arrays are merging in a concatenative way. Using + instead of a comma separation does not create 2 arrays in an array, but 2 objects in an array.

2 answers

1

You could concat primaryData and secondaryData and map then the value of label with the remainder operator and the value of the iterating array.

var primaryData = [1, 2],
    secondaryData = [3, 4],
    label = ['label1', 'label2'],
    result = primaryData.concat(secondaryData).map(function(a, i) {
        return [label[i % 2], a.toString()];
    });
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
1

Вы можете использовать простой цикл»

var data = [];

for(var i = 0; i < 4; i++) {
  data.push(["label" + (i % 2 + 1), (i + 1).toString()]);
} 

console.log(data);