0

I have a list of projects as followings:

projects = [{name: '1',
             agencies: ['USA', 'China']},
            {name: '2',
             agencies: ['Japan', 'Russia']}]

I want to get the result ['USA', 'China', 'Japan', 'Russia'], currently I use the following code, but I would like to know if there is better solution (one line code) using map function:

const agencies = [];
projects.forEach((project) =>
        project.agencies.forEach((agency) => {
            agencies.push(agency);
        })
);
4
  • 1
    I'm voting to close this question as off-topic because it is asking for a better way to do already existing code. ask on Code Review Commented Jan 25, 2018 at 20:47
  • 3
    const agencies = [].concat(...projects.map(x => x.agencies)) for a one liner. Commented Jan 25, 2018 at 20:49
  • This is definitely what I want. Could you post it as answer? Commented Jan 25, 2018 at 20:51
  • 1
    var agencies = projects.reduce((arr, p) => [...arr, ...p.agencies], []) :D Commented Jan 25, 2018 at 21:09

3 Answers 3

1

Here is a simple one-liner to accomplish this:

const projects = [{
  name: '1',
  agencies: ['USA', 'China']
}, {
  name: '2',
  agencies: ['Japan', 'Russia']
}]

const agencies = [].concat(...projects.map(x => x.agencies));
console.log(agencies)

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

Comments

1

returned maps, by definition, will always be of the same length as the array used to generate it.

You should probably use reduce instead, to generate a different length array like you want.

try:

 projects.reduce((acc, project) => [...acc, ...project.agencies], [])

Comments

1

I would use destructuring, reduce and concat:

  agencies.reduce((res, {agencies}) => res.concat(agencies));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.