0

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

chris97ong
  • 6,870
  • 7
  • 32
  • 52
user3370945
  • 11
  • 1
  • 3

4 Answers4

1

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('-')
}));
vaultah
  • 44,105
  • 12
  • 114
  • 143
  • Arrays should never be iterated with `for (x in arr)` syntax as that iterates iterable properties, not just array elements. – jfriend00 Jun 24 '14 at 06:01
1

Try this

var arr = [["a","b"],["a","c"],["b","c"]];

    for(var i=0;i<arr.length;i++)
    {
        console.log(arr[i].join("-"));

    }
Unknownman
  • 473
  • 3
  • 9
0

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.

Community
  • 1
  • 1
Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
0

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"
Amberlamps
  • 39,180
  • 5
  • 43
  • 53