2

I've an array which contains the objects including various key and values. I'm going to pick out the certain values from the Array and check if the specific value is included or not in the Array.

function groupByName (contract) {
 const { age } = contract;

 const groups = [
  {name: 'John', age: 30},
  {name: 'Jack', age: 33},
  {name: 'Tom', age: 40}
  ...
 ];
 ...
}

In order to compare the age in groups array, right now I have to use loop functions and then check one by one. Like

groups.forEach(g => {
 if (g.age === age) {
  ...
 } else {
  ...
 }
});

But I don't like this approach and think there are simple and effective way. Please help me!

cbenitez
  • 301
  • 1
  • 8
  • 4
    `groups.filter(g => g.age == age)` try with this – flyingfox Nov 17 '22 at 08:53
  • @lucumt: There's an if/else in the code, so your suggestion won't necessarily help. It really depends on what's inside that if/else (more specifically, what's inside the 'else' part, since your filter basically skips every element which is dealt with inside that part). The question in general isn't very informative when it asks for a "simple and effective way", since the question is - a simple and effective way for doing what? –  Nov 17 '22 at 08:56
  • What is the expected output? – adiga Nov 17 '22 at 09:23
  • Does this answer your question? [How to filter object array based on attributes?](https://stackoverflow.com/questions/2722159/how-to-filter-object-array-based-on-attributes) – Gishas Nov 17 '22 at 09:26

2 Answers2

3

you can use filter to create two sublists

like this

const groups = [
  {name: 'John', age: 30},
  {name: 'Jack', age: 33},
  {name: 'Tom', age: 40}
  ]
  
const withAge = age => groups.filter(g => g.age === age)
const withoutAge = age => groups.filter(g => g.age !== age)

const age30 = withAge(30)

const ageNot30 = withoutAge(30)

age30.forEach(g => {
  console.log('do some stuff with age 30', g)
})

ageNot30.forEach(g => {
  console.log('do some stuff without age 30', g)
})
R4ncid
  • 6,944
  • 1
  • 4
  • 18
2

maybe you can see this function

groups.some(p=>r.age===age)//if there is a object meet the criteria, return true, else return false

or read this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

by the way, if you want to execute the if/else snippet in every loop, maybe you should use forEach

corcre
  • 21
  • 3