Given array of parameters, make array from array of objects

Viewed 39

I have this array:

course_ids: [11, 70, 3]

And this array of objects:

arr: [{
    course_id: 11,
    course_hour_id: 56,
    name: 'John',
},
{
    course_id: 70,
    course_hour_id: 72,
    name: 'Lily',
},{
    course_id: 3,
    course_hour_id: 12,
    name: 'Mike',
}]

Given these two, I want to make an array of course_hour_ids: [56, 72, 12] How can I do that using React.js?

4 Answers

At first filter then map

let objArray = [
  {
    course_id: 11,
    course_hour_id: 56,
    name: 'John',
  },
  {
    course_id: 70,
    course_hour_id: 72,
    name: 'Lily',
  },
  {
    course_id: 3,
    course_hour_id: 12,
    name: 'Mike',
  }
];

let course_ids = [11, 70, 3];

let result = objArray.filter(array => course_ids.some(filter => filter == array.course_id)).map(a => a.course_hour_id);
console.log(result);

You colud filter initial array and then map the result array on course_hour_id like:

let arr = [
{
course_id: 11,
course_hour_id: 56,
name: 'John',
},
{
course_id: 70,
course_hour_id: 72,
name: 'Lily',
},{
course_id: 3,
course_hour_id: 12,
name: 'Mike',
}
]

let course_ids = [11, 70, 3];

let res = arr.filter(el => {
   return course_ids.includes(el.course_id);
})

console.log(res.map(el => el.course_hour_id))

const course_ids = [11, 70, 3];
const arr = [{
    course_id: 11,
    course_hour_id: 56,
    name: 'John',
  },
  {
    course_id: 70,
    course_hour_id: 72,
    name: 'Lily',
  }, {
    course_id: 3,
    course_hour_id: 12,
    name: 'Mike',
  }
];

const result = arr.map(x => {
  if (course_ids.includes(x.course_id))
    return x.course_hour_id
});
console.log(result)

No need to use .filter

  course_ids
    .map(course_id =>
      arr.find(arrItem =>
        arrItem.course_id === course_id)
        ?.course_hour_id);

The above solutions uses optional chaining. If you don't use that you can write:

  course_ids
    .map(course_id =>
      arr.some(arrItem =>
        arrItem.course_id === course_id)
        ? arr.find(arrItem =>
          arrItem.course_id === course_id).course_hour_id
        : null
    );
Related