1

I have an array of objects which are all instances of the same class like below:

class Foo {
    constructor(bar){
        this.bar = bar;
    }
}

var myArr = [new Foo("1"), new Foo("2"), new Foo("3"), new Foo("4")];

I want to be able to join the bar property of each object in the array into a comma separated string.

Is it possible to call the .join method on the property of an object? If not is below the most efficent way to do this?

 var result = "";
 for (var i = 0; i < myArr.length; i++){
     result += myArr[i].bar+","
 }

Or is there another way?

Adam Griffiths
  • 680
  • 6
  • 26
  • 60

3 Answers3

2

You can use Array.prototype.map:

var myArr = [
  {bar: "Joe", age: 22},
  {bar: "Kevin", age: 24},
  {bar: "Peter", age: 21}
];

console.log(myArr.map(function(x) { return x.bar; }).join(','));
LWC
  • 1,084
  • 1
  • 10
  • 28
iulian
  • 5,494
  • 3
  • 29
  • 39
2

You could use Array.prototype.reduce:

var myArr = [
  {bar: "Joe", age: 22},
  {bar: "Kevin", age: 24},
  {bar: "Peter", age: 21}
];

console.log(myArr.reduce(function(acc, el) {
     if(!acc) return el.bar;
     return acc + ', ' + el.bar;
}, ''));
LWC
  • 1,084
  • 1
  • 10
  • 28
Max Kroshka
  • 457
  • 2
  • 5
  • I think this is the "correct" approach. Mapping a collection to a single value is a reduction, strictly speaking. It will save a loop over mapping + joining as well. – William B May 04 '16 at 21:12
0

The alternative solution using Array.reduce function:

var barValues = myArr.reduce((a,b) => (a['bar'] || a) + "," + b['bar']);
console.log(barValues);  // "1,2,3,4"
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105