-2

I have 2 arrays

One is an array that contains every project:

let allProjects = [{project_id: 1, name: "project 1"}, {project_id: 2, name: "project 2"}, {project_id: 3, name: "project 3"}, {project_id: 4, name: "project 4"}]

And one contains only project ids

let selectedProjects = [{project_id: 1}, {project_id: 2}]

How can I get the names from allProjects array and return a new array containing name and id according to the Id's that are provided in the selectedProjects array?

networkcore
  • 135
  • 1
  • 11

1 Answers1

0

You can use a combination of filter, map and includes:

console.log(allProjects
            .filter(project => selectedProjects
                               .map(p => p.project_id)
                               .includes(project.project_id)));

Output:

[
  { project_id: 1, name: 'project 1' },
  { project_id: 2, name: 'project 2' }
]

Probably there is a way to avoid map but for me map focuses the intention.

Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62