-2

I have an array:

people = [
  {name: a, group: 1},
  {name: b, group: 2},
  {name: c, group: 3},
  {name: d, group: 2},
  {name: e, group: 3},
  {name: f, group: 1},
  {name: g, group: 1},
];

I need to find all people, who are in groups 2 and 3. Desired output:

filteredPeople = [
  {name: b, group: 2},
  {name: c, group: 3},
  {name: d, group: 2},
  {name: e, group: 3},
];

It might be other groups as well (groups using for search may change).

How I have to do that?

Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
  • `filteredPeople = people.filter(i => [2,3].includes(i.group));`...? – briosheje Jul 25 '19 at 09:02
  • 3
    Possible duplicate of [filtering an array of objects based on another array in javascript](https://stackoverflow.com/questions/46894352/filtering-an-array-of-objects-based-on-another-array-in-javascript) and [Filter array of objects by multiple values](https://stackoverflow.com/questions/53576285) and [Filter array of objects by multiple properties and values](https://stackoverflow.com/questions/44330952) – adiga Jul 25 '19 at 09:05
  • @adiga oh, nice catch. Didn't find that. – briosheje Jul 25 '19 at 09:05
  • might help https://stackoverflow.com/q/31831651/3514144 – Ajay Pandya Jul 25 '19 at 09:05

3 Answers3

1

You can use .filter() and .includes() methods to get the desired output:

const data = [
  {name: 'a', group: 1}, {name: 'b', group: 2}, {name: 'c', group: 3},
  {name: 'd', group: 2}, {name: 'e', group: 3}, {name: 'f', group: 1},
  {name: 'g', group: 1}
];

const groups = [2, 3];

const result = data.filter(({ group }) => groups.includes(group));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
1

filter and includes do the job here. We use the rest operators (which gives us an array on which we can apply includes). So you can put any number of groups into the function call to be flexible when filtering.

let people = [{name: "a",group:1},{name: "b",group:2},{name: "c",group:3},{name:"d",group:2},{name:"e",group:3},{name:"f",group:1},{name:"g",group:1}];

let filterGroups = (arr, ...groups) => arr.filter(o => groups.includes(o.group));

console.log(filterGroups(people, 2, 3));
claasic
  • 1,050
  • 6
  • 14
0

Using Array.prototype.filter() and the expression 2 === group || group === 3

const data = [{name: 'a', group: 1}, {name: 'b', group: 2}, {name: 'c', group: 3}, {name: 'd', group: 2}, {name: 'e', group: 3}, {name: 'f', group: 1}, {name: 'g', group: 1}];
const result = data.filter(({ group }) => group === 2 || group === 3);

console.log(result);
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46