skip to Main Content

Array Given:

const Collection = [{ id: 1 }, { id: 3 }, { id: 2 }, { id: 4 }]

Required String should be:

string = "1,3,2,4"

I have tried to get from forEach() loop to join() each value and save it in a string variable.

expecting result should be a comma separated string.

2

Answers


  1. The forEach() method doesn’t return anything. Instead you want to map() each element to its id property, and then join() it:

    const collection = [{ id: 1 }, { id: 3 }, { id: 2 }, { id: 4 }];
    console.log(collection.map(x => x.id).join()); // "1,3,2,4"
    

    Note that the join() method takes care of converting the numbers to strings and adding commas (","), which are the default separators.

    Playground link to code

    Login or Signup to reply.
  2. You can use forEach, but you would have to pair it with something else.

    const Collection = [{ id: 1 }, { id: 3 }, { id: 2 }, { id: 4 }];
    var res = [];
    
    Collection.forEach(function(item) {
        res.push(item.id);
    });
    
    res = res.join(",");
    console.log(res);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search