Delina Rahayu
Delina Rahayu

Reputation: 65

Concat two arrays which one of them is also an array

How do I concat two arrays which one of them is also an array. It looks like this

let stat = [
  ["completed", "0", "0", "0"],
  ["due", "1", "2", "2"],
  ["warning", "0", "0", "0"]
]

let val = [
  [0, 0, 0],
  [1, 2, 2],
  [0, 0, 0]
]



var arr = [];
for (var i = 0; i < stat.length; i++) {
  var temp = [stat[i][0].concat([val[i]])];
  arr.push(temp);
}
console.log(arr)

When console.log, it will print out:

["Completed0,0,0"]
["Due1,2,2"]
["Warning0,0,0"]

and I want the result looks like this:

["Completed", 0, 0, 0]
["Due", 1, 2, 2]
["Warning", 0, 0, 0]

How can I get new array like that? Thank you!

Upvotes: 1

Views: 139

Answers (3)

user1636522
user1636522

Reputation:

Following up on mplungjan's comment, why not using only one array?

stats = [
  ["completed", "0", "0", "0"],
  ["due", "1", "2", "2"],
  ["warning", "0", "0", "0"]
];

stats2 = stats.map(function (x) {
  return [
    x[0],
    parseInt(x[1], 10),
    parseInt(x[2], 10),
    parseInt(x[3], 10)
  ];
});

for (i = 0; i < stats2.length; i++) {
  console.log(JSON.stringify(stats2[i]));
}

Upvotes: 0

Hrishi
Hrishi

Reputation: 1250

let stat = [
  ["completed", "0", "0", "0"],
  ["due", "1", "2", "2"],
  ["warning", "0", "0", "0"]
]

let val = [
  ["0", "0", "0"],
  ["1", "2", "2"],
  ["0", "0", "0"]
]


var arr = [];
for (var i = 0; i < stat.length; i++) {
  var temp = stat[i].concat(
    val[i].filter(x => !stat[i].includes(x))
  );
  arr.push(temp);
}
console.log(arr);

Upvotes: 5

Nina Scholz
Nina Scholz

Reputation: 386550

You get a string result in the array, because you take the first item of the array and use concat, which works for strings (String#concat) as well as for arrays (Array#concat), but in case of a string, the parameter is converted to string. The result is a sting, not single values of an array.

var stat = [["completed", "0", "0", "0"], ["due", "1", "2", "2"], ["warning", "0", "0", "0"]],
    val = [[0, 0, 0], [1, 2, 2], [0, 0, 0]],
    arr = [];

for (var i = 0; i < stat.length; i++) {
    var temp = [stat[i][0]].concat(val[i]);
    arr.push(temp);
}
console.log(arr)

A shorter approach is to map the first item with the values of val.

var stat = [["completed", "0", "0", "0"], ["due", "1", "2", "2"], ["warning", "0", "0", "0"]],
    val = [[0, 0, 0], [1, 2, 2], [0, 0, 0]],
    result = stat.map(([v], i) => [v, ...val[i]]);

console.log(result);

Upvotes: 1

Related Questions