-2

Help, please.

How is it possible in JS to transform these arrays:

$ar1 = array('Shop 1', 15, 25, 30);
$ar2 = array('Shop 2', 25, 45, 50);
$ar3 = array('Month', 1, 2, 3);

to this:

$values = array(
   array('Month', 'Shop 1', 'Shop 2'),
   array('1', 15, 25),
   array('2', 25, 45),
   array('3', 30, 50),
);

in PHP I can do it as follow:

$result = array_map(function($a,$b,$c){ return [$a,$b,$c]; }, $ar3,$ar1,$ar2);

or like that:

function flip($arr) {
$result = array();
foreach ($arr as $index => $list) {
    foreach ($list as $key => $value) {
        $result[$key][$index] = $value;
    }
}
return $result;
}

$values = flip([$ar3, $ar1, $ar2]);
1

3 Answers 3

0

You can use Array.prototype.map in Javascript. It passes the array index as an argument to the callback, which you can then use to access the other two arrays.

var arr1 = ['Shop 1', 15, 25, 30];
var arr2 = ['Shop 2', 25, 45, 50];
var arr3 = ['Month', 1, 2, 3];

var result = arr3.map(function(element, index) {
  return [element, arr1[index], arr2[index]];
});

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

0

You could try something like this:

var arr1 = ['Shop 1', 15, 25, 30];
var arr2 = ['Shop 2', 25, 45, 50];
var arr3 = ['Month', 1, 2, 3];

var res = [];
Object.keys(arr3)
      .forEach(function(key){
          res.push([arr3[key].toString(), arr1[key], arr2[key]]); 
});

console.log(res);

Comments

0

With proper arrays, you could transform the single arrays with a nested loop for the result.

var array1 = ['Shop 1', 15, 25, 30],
    array2 = ['Shop 2', 25, 45, 50],
    array3 = ['Month', 1, 2, 3],
    result = [array3, array1, array2].reduce(function (r, a, i) {
        a.forEach(function (b, j) {
            r[j] = r[j] || [];
            r[j][i] = b;
        });
        return r;
    }, []);

console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.