var mahasiswa = new Array();
mahasiswa[0] = new Array("100000001", "Alda", "man", "1 Mei 1994", "DKV");
mahasiswa[1] = new Array("100000002", "Aldi", "woman", "2 Mei 1994", "Seni");
mahasiswa[2] = new Array("100000003", "Aldo", "man", "3 Mei 1994", "Seni");
mahasiswa[3] = new Array("100000004", "Alfi", "man", "4 Mei 1994", "Akutansi");
mahasiswa[4] = new Array("100000005", "Andi", "man", "5 Mei 1994", "Seni");
mahasiswa[5] = new Array("10000006" , "Bandri","woman", "6 Mei 1994", "DKV");
how I can print name of woman only? The name is at inex 1 (Alda/Aldi etc).
-
Please edit your question to match the title (or vice-versa). Are you asking about how to print something, or how to create an array?anderas– anderas2015年02月27日 10:20:59 +00:00Commented Feb 27, 2015 at 10:20
5 Answers 5
If you don't really need an array, it would be much easier to use an object.
Think of an object as a map with key value.
var mahasiswa = [];
mahasiswa.push({
id: "100000001",
name:"Alda",
gener: "man",
someDate: "1 Mei 1994
});
mahasiswa.push({
id: "100000001",
name:"Alda",
gender: "woman",
someDate: "1 Mei 1994
});
Then you could use something like this:
for(var i=0;i<mahasiswa.length;i++){
var person = mahasiswa[i];
if(person.gender === "woman"){
console.log(mahasiswa[i].name)
}
}
If you really need an Array, then do something like this:
for(i=0; i< mahasiswa.length; i++){
var person = mahasiswa[i];
if(person [2]=='woman'){
console.log(person)
}
}
Some background infos here: 1) If you initialize an array in Javascript, better use this the [] instead of new Array(). It's much faster (See this: http://jsperf.com/literal-vs-new-23)
2) If possible, use an object over an array. it's much more flexible
3) Remember, objects are unsorted where arrays are sorted
Comments
I think the only way is to go through the whole array.
for(i=0;i<= mahasiswa.length;i++){
if(mahasiswa[i][2]=='woman'){
//...
}
}
otherwise you should rearrange your array and sort it for gender in first dimension.
Comments
You can check if the entry is a woman by using this:
mahasiswa[n][2] == "woman"
So, using a for loop, you can print out the names of women only:
for (var i = 0, len = mahasiswa.length; i < len; i++){
if (mahasiswa[i][2] == "woman"){
console.log(mahasiswa[i][1]);
}
}
But normally, in javascript, you wouldn't define an array like this as an array of arrays, but of objects.
Comments
Using this structure you can filter and map the array:
mahasiswa.filter( function( item ){
return item[2] == "woman";
}).map( function( item ){
return item[1]
}); // ["Aldi", "Bandri" ]
2 Comments
You could use filter to get the 'woman' elements, and then just print the name(s) of each of them:
mahasiswa.filter(function (el) {
return el[2] === 'woman';
}).forEach(function (el) {
console.log(el[1])
});