0

I'm new to javascript and have a simple task. I have an array "values" and a second array "gender", and I want to create a third array which is "values" where gender == "Males". The variables look like this:

var values = new Array();
values[0] = .1
values[1] = .3
values [2] = .7
values[3] = .8
var gender = new Array();
gender[0]='Males'
gender[1]='Males'
gender[2]='Females'
gender[3]='Females'

The equivalent syntax in python would be:

female_values = values[gender=='Females']

Any thoughts?

1
  • 1
    I don't know what Python you program in, but in my version the syntax for what you want would be something like female_values = [values[i] for i, sex in enumerate(gender) if sex == 'Females']. Commented Nov 15, 2011 at 6:10

2 Answers 2

2
var values = [.1, .3, .7, .8];
var gender = ['Males', 'Males', 'Females', 'Females'];

var males = [];
for (var i = 0; i < values.length; i++) {
  if (gender[i] == 'Males') {
    males.push(values[i]);
  }
}

The Array constructor is not usually used, use the array literal [] instead. Then simply loop through the arrays and push the value onto the third array if some condition that you set passes.


And yeah this is more pain than python, although coffee script can make it a little nicer.

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

4 Comments

Great, thanks for the answer and general feedback (I'm just getting started).
Not that it matters much in small arrays, but you should cache the length of the array in a temporary variable so that it doesn't have to be calculated for every iteration.
Quick related question -- if I only want to identify a single value, is there a way to do it without looping? Thanks.
Javscript has almost no native support for any kind of snazzy iteration. So anytime you want an item/items from an array and you don't know the index aleady, then you have to loop. No way around it.
0

nicer way

var values = [.1, .3, .7, .8],
    gender = ['Males', 'Males', 'Females', 'Females'],
    males  = [],
    i      = values.length;

while ( i-- ) {
    gender[i] == 'Males' && males.unshift(values[i])
}

2 Comments

Adjectives like nice can be quite subjective. You version is probably ever so slightly faster, but its less readable because it relies on a bit more magic especially for a javascript beginner. Also the items in the resulting array will be reversed with this approach.
yes, sorry, result is reversed there. Replaced the push with unshift. Should be fine now.

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.