0

I have an array

const newChecked = ["recreational", "charity"]

and an object

const allActivities = [
  {activity: '...', type: 'social', },
  {activity: '...', type: 'social', },
  {activity: '...', type: 'charity', },
  {activity: '...', type: 'recreational', },
]

And I want to get a new object, that does not contain type that are contains in newChecked. In other words, newActivitiesList should contain data with type of "social".

const newActivitiesList = allActivities.filter((item) =>
  newChecked.map((i) => {
    return item.type !== i;
  })
);
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Festina
  • 327
  • 3
  • 17

2 Answers2

1

You can use Array#filter in conjunction with Array#includes.

const newChecked = ["recreational", "charity"]
const allActivities = [
{activity: '...', type: 'social', },
{activity: '...', type: 'social', },
{activity: '...', type: 'charity', },
{activity: '...', type: 'recreational', },
];
const res = allActivities.filter(({type})=>!newChecked.includes(type));
console.log(res);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
1

You can use Array.prototype.reduce function to create a new array

const newChecked = ["recreational", "charity"]

const allActivities = [
  {activity: '...', type: 'social', },
  {activity: '...', type: 'social', },
  {activity: '...', type: 'charity', },
  {activity: '...', type: 'recreational', },
];

const newActivitiesList = allActivities.reduce((accumulator, current) => {
  if(newChecked.indexOf(current.type) === -1) {
    return accumulator.concat(current);
  } else {
    return accumulator;
  }
},[]);

console.log(newActivitiesList);
Yves Kipondo
  • 5,289
  • 1
  • 18
  • 31