1

I have a JavaScript array as shown below

var userMale = [];
var userData = [
                {userId: "100", userName: "John", gender: "M"},
                {userId: "101", userName: "Emma", gender: "F"},
                {userId: "102", userName: "Alex", gender: "F"},
                {userId: "103", userName: "Sam", gender: "M"}
              ]

I need to get all userIds in to a different array based on gender condition, i.e. All males should be in userMale array

I have written below code to achieve that. It works, however, I am looking to avoid for and if loops

for(var i=0; i<userData.length; i++) {
    if(userData[i].gender == "M") {
        userMale.push(userData[i].userId);
    }
}

console.log("userMale: ", userMale);

6 Answers 6

4

You can use filter.

var userData = [
                {userId: "100", userName: "John", gender: "M"},
                {userId: "101", userName: "Emma", gender: "F"},
                {userId: "102", userName: "Alex", gender: "F"},
                {userId: "103", userName: "Sam", gender: "M"}
              ]
              
let userMale = userData.filter(data => {
  return data.gender === "M"
})

console.log(userMale)

Sign up to request clarification or add additional context in comments.

2 Comments

I just need userIds i.e. 100, 103 in the array. Not the entire data
Okay, you can append map. let userMale = userData.filter(data => { return data.gender === 'M' }).map((value) => { return value.userId; });
1

Since you want to filter and project the elements onto userId at the same time, an approach using Array.reduce seems the best fit. See here:

var userData = [
                {userId: "100", userName: "John", gender: "M"},
                {userId: "101", userName: "Emma", gender: "F"},
                {userId: "102", userName: "Alex", gender: "F"},
                {userId: "103", userName: "Sam", gender: "M"}
              ];
              
const convert = (data) => data.reduce((result, { userId, gender }) => {
  if (gender === 'M') {
    return result.concat(userId);
  } 
  
  return result;
}, []);   

var userMale = convert(userData);

console.log(userMale);

1 Comment

This is a better approach since it needs to loop once rather than twice as in Danijel's answer.
1

All you need is using filter function

var userData = [
                    {userId: "100", userName: "John", gender: "M"},
                    {userId: "101", userName: "Emma", gender: "F"},
                    {userId: "102", userName: "Alex", gender: "F"},
                    {userId: "103", userName: "Sam", gender: "M"}
                  ]

    let userMale = userData.filter(data => {
      return data.gender === "M"
    })

    let userFemale = userData.filter(data => {
      return data.gender === "F"
    })

1 Comment

I just need userIds i.e. 100, 103 in the array. Not the entire data
1

You can use reject of Underscore.js

reject returns the values in list without the elements that the truth test (predicate) passes.

var userMale = _.reject(userData, function(item){ return item.gender != "M"; });

Comments

1

Using vanilla JavaScript :

var userData = [
  {userId: "100", userName: "John", gender: "M"},
  {userId: "101", userName: "Emma", gender: "F"},
  {userId: "102", userName: "Alex", gender: "F"},
  {userId: "103", userName: "Sam", gender: "M"}
];

function getMaleFemale ()
{
  // Create an array for each gender
  let male = [], female = [];
  
  // For each user, check if gender is F, if so, push id to female else to male
  userData.forEach( user => ( user.gender === 'F' ? female : male ).push( user.userId ) );
  
  // Return male and female
  return { male, female };
}

// Usage example
let { male, female } = getMaleFemale();

// Do something with male and female

console.log( 'male :', male );
console.log( 'female :', female );

Comments

0

A concise version of FK82's approach.

let userMale = userData.reduce((result, user) =>
    user.gender === 'M' ? result.concat(user.userId) : result
, [])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.