0

Below is the code I am trying out to filter out the array for males and females. But it seems it is returning the whole array again in both male and female variables.

  const male = await familyTree.filter(async(uncle) => {uncle.gender === 'Male'}); 

  const female = await familyTree.filter(async(aunt) => {aunt.gender === 'Female'});

My array of objects:

var familyTree=  [
  {
    name: 'Ish',
    gender: 'Male',
    grandfather: 'null',
    grandmother: 'null',
    father: 'Shan',
    mother: 'Anga',
    wife: {}
  },
  {
    name: 'Vich',
    gender: 'Male',
    grandfather: 'null',
    grandmother: 'null',
    father: 'Shan',
    mother: 'Anga',
    wife: {
      name: 'Lika',
      husband: 'Vich',
      fil: 'Shan',
      mil: 'Anga',
      children: [Array]
    }
  },
  {
    name: 'Aras',
    gender: 'Male',
    grandfather: 'null',
    grandmother: 'null',
    father: 'Shan',
    mother: 'Anga',
    wife: {
      name: 'Chitra',
      husband: 'Aras',
      fil: 'Shan',
      mil: 'Anga',
      children: [Array]
    }
  },
  {
    name: 'Satya',
    gender: 'Female',
    grandfather: 'null',
    grandmother: 'null',
    father: 'Shan',
    mother: 'Anga',
    husband: 'Vyan',
    children: [ [Object], [Object], [Object] ]
  }
]

When I print males and females in the console it is returning the whole array again without filtering them. What could be the reason?

Bunny808
  • 1
  • 1
  • 1
    You're missing `return` in both your filter methods. – Henry Ecker Apr 10 '21 at 20:51
  • Also: `filter` does not return a promise, not even when you pass it an `async` function as callback, and so awaiting the result of `filter` is not of much use. There is no need for `async` nor `await` in your code, as there is no sign of an asynchronous dependency. – trincot Apr 10 '21 at 20:53

3 Answers3

2

If you use {} in an arrow function, you need to return the results from it.

I also removed the async-awaits please reintroduce them if they were necessary.

const male = familyTree.filter((uncle) => {
    return uncle.gender === 'Male'
});

const female = familyTree.filter((aunt) => {
    return aunt.gender === 'Female'
});
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
1

For filtering through an array in JavaScript, you can use a simplified way

var males = familyTree.filter(prop => {
    return prop.gender === 'Male'
}) 

var females = familyTree.filter(prop => {
    return prop.gender === 'Female'
}) 
masud_moni
  • 1,121
  • 16
  • 33
0

when you use curly braces to enclose function body {}, you need to use return keyword to return a value,

const male = familyTree.filter(uncle => {return uncle.gender === 'Male'});

or if you remove the curly braces:

const male = familyTree.filter(uncle => uncle.gender === 'Male')
Salma
  • 26
  • 1
  • 6