I have an array in the following format.
var arr = [[a,b],[a,c],[b,c]];
My problem is simply printing arr is giving a,b,a,c,b,c
i was expecting, to iterate it and get single combo at a time.
How is it possible to access it in
a-b a-c b-c
I have an array in the following format.
var arr = [[a,b],[a,c],[b,c]];
My problem is simply printing arr is giving a,b,a,c,b,c
i was expecting, to iterate it and get single combo at a time.
How is it possible to access it in
a-b a-c b-c
Try this:
for (var x = 0; x < arr.length; x++)
console.log(arr[x].join('-'))
The above outputs
a-b
a-c
b-c
Just for diversity, another possible way:
console.log.apply(null, arr.map(function(v) {
return v.join('-')
}));
Try this
var arr = [["a","b"],["a","c"],["b","c"]];
for(var i=0;i<arr.length;i++)
{
console.log(arr[i].join("-"));
}
Use a normal for loop for this and use the built-in method of #join on the array itself if you want that exact output you have specified.
for(var i = 0; i < arr.length; i++) {
console.log(arr[i].join('-'));
}
Looping over arrays with the for...in construct should never be done as you're not looping over what you think you're looping over.
The for...in
loops over the enumerable properties of an object. Great post about how and why's here.
I am assuming that you meant
var arr = [["a","b"],["a","c"],["b","c"]];
Because otherwise the toString()
function does not return a-b a-c b-c
but rather the values of those variables.
Here is another solution where you work on the output string directly:
var arr = [["a","b"],["a","c"],["b","c"]];
arr.toString().replace(/,/g, '-').replace(/(\w+-\w+)-/g, "$1 ")
// => "a-b a-c b-c"