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?

0

3 Answers 3

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(','));

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

Comments

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;
}, ''));

1 Comment

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.
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"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.