Tamane
Tamane

Reputation: 35

How to add to an array in an array JavaScript

I have an array:

["1", "2","3","4","5"]

that I would like to change to:

[["1, 0 ,0 ,0"], ["2, 0, 0, 0"],["3,0,0,0"],["4,0,0,0"],["5,0,0,0"]]

I've tried to achieve this with the following code:

var arr1 = ["1", "2","3","4","5"];
var arr2 = [,"0", "0","0"];

for(var z=0; z<arr1.length; z++)
    {
    arr1[z] = arr1[z].concat(arr2);
    console.log(arr1)
    }
 

However, this doesn't achieve what I want and places commas between each item, which I think is because it is not a string? I've tried using .join too but I couldn't get that to work either. Could someone point me in the right direction for this please? Thanks.

Upvotes: 2

Views: 111

Answers (4)

Abhishek Bhagate
Abhishek Bhagate

Reputation: 5786

You first need to convert each element to array and then append the second array to the newly converted array element. The following code snippet would make it clear -

var arr1 = ["1", "2", "3", "4", "5"];
var arr2 = [ "0", "0", "0"];

for (var z = 0; z < arr1.length; z++) {
  // First convert the element into a list
  arr1[z] = [arr1[z]];
  // Then append the second array to it
  arr1[z] = arr1[z].concat(arr2);
  // Another way -
  //arr1[z].push(...arr2);

}

// Final array -
console.log(arr1);


Using Map() :

Another way to do it would be using map() as below -

var arr1 = ["1", "2", "3", "4", "5"];
var arr2 = [ "0", "0", "0"];

arr1 = arr1.map(el=>[el,...arr2]);
console.log(arr1);


Using ForEach()

You could also do it using forEach() method -

var arr1 = ["1", "2", "3", "4", "5"];
var arr2 = [ "0", "0", "0"];
// this will note mutate original arr1 and store result in res
let res = [];

// ... is the spread operator which will allows iterable objects to be expanded in place
arr1.forEach(el=>res.push([el,...arr2]));

// final result
console.log(res);


There's probably numerous other ways as well... These were just few I have listed. You could even do it using naive nested loops method if you don't know anything about map(), forEach(), or concat() / push() methods.

Hope this helps !

Upvotes: 1

EugenSunic
EugenSunic

Reputation: 13743

Use map to go through each of your element and append the array with zeros, transform it to a string and wrap in an array again which will hold one value

const a = ["1", "2", "3", "4", "5"]
const arr = [0, 0, 0, 0];
const res = a.map(x => [
  [x, ...arr].join()
])
console.log(res)

Upvotes: 1

tachko
tachko

Reputation: 161

if it's set in stone, you can do

let arr = []

var arr1 = ["1", "2","3","4","5"];
var arr2 = ["0", "0","0"];

arr1.forEach(el=>arr.push([el, ...arr2]));


console.log(arr)

Upvotes: 1

Mario
Mario

Reputation: 4998

Please try the following example

const array = ["1", "2", "3", "4", "5"];
const output = array.map((entry) => [`${entry}, 0, 0, 0`]);

console.log(output);

See

Upvotes: 1

Related Questions