1

I have written down my first JavaScript code to do some dynamic rendering in a webpage:

var c_names = ["Canada", "USA", "israel"]
var c_ids = [1, 2, 3]
var c_domaain = ["www.canada.com", "www.usa.com", "www.israel.com"]

var data_1 = []
var C_data = [
  ['Country', 'ids', 'Domain']
]
var x = 1


for (i = 0; i == 3; i++) {
  var x = x + 1
  data_1.push(c_name[x], c_ids[x], c_domain[x])
  for (i = 0; i < c_name.length; i++) {
    C_data.push(data_1)
  }
}

console.log(C_data)

I'm expecting this output:

 data = [ ['Country', 'ids', 'Domain'],
           ['USA', 1, 'www.usa.com'],
           ['Canada', 2, 'www.usa.com'],
           ['Israel', 3, 'www.usa.com'],
]

4 Answers 4

1

Iterate over one of the arrays and then append the respective items.

var names   = ["Canada", "USA", "israel"]
var ids     = [1, 2, 3]
var domains = ["www.canada.com", "www.usa.com", "www.israel.com"]

var data = [
    ["Country", "ID", "Domain"]
]

names.forEach ((name, idx) => {
    data.push ([ name, ids [idx], domains [idx]]);
});

console.log(data)

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

Comments

0

You could take the array in one array and iterate the outer and the the inner array while respecting the index.

var c_names = ["Canada", "USA", "israel"],
    c_ids = [1, 2, 3],
    c_domaain = ["www.canada.com", "www.usa.com", "www.israel.com"],
    c_data = ['Country', 'ids', 'Domain'],
    result = [c_names, c_ids, c_data].reduce(function (r, a) {
        a.forEach(function (b, i) {
            r[i] = r[i] || [];
            r[i].push(b);
        });
        return r;
    }, []);

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

Comments

0

var c_names = ["Canada", "USA", "israel"]
var c_ids = [1, 2, 3]
var c_domaain = ["www.canada.com", "www.usa.com", "www.israel.com"]
var C_data = [
  ['Country', 'ids', 'Domain']
]
var i = -1;
while ( c_names[++i] ) { 
  C_data.push( [ c_names[i], c_ids[i], c_domaain[i]] );
}
console.log(C_data)

Comments

0

var c_names = ["Canada","USA","israel" ];
var c_ids =  [1,2,3];
var c_domaain = ["www.canada.com","www.usa.com","www.israel.com"];

var data_1 = [];
var C_data = ['Country', 'ids', 'Domain'];
var x = 1;

for(var i = 0; i < c_names.length; i++){
  data_1.push(new Array(C_data[i], c_names[i], c_domaain[i]));
};
console.log(data_1);

This is the output of your code which is wrong:

[ [ "Country", "ids","Domain"],
  [ "Canada", 1, "Country"],
  [  "USA",  2,  "ids" ],
  [  "israel", 3, "Domain"]
]

2 Comments

A little mistake with values... c_ids[i] instead of C_data[i].
I have edited your answer to show output kindly check your code Thanks

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.