Last active
August 29, 2015 14:04
-
-
Save jczaplew/1bdfd9802d84c7d678a9 to your computer and use it in GitHub Desktop.
Array.map confusion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var data = [ | |
{"name": null}, | |
{"name": "a"}, | |
{"name": "b"}, | |
{"name": null}, | |
{"name": null}, | |
{"name": "c"} | |
]; | |
var doesNotWork = data.map(function(d) { | |
if (d.name && d.name.length) { | |
return d.name; | |
} | |
}); | |
var works = []; | |
data.map(function(d) { | |
if (d.name && d.name.length) { | |
works.push(d.name); | |
} | |
}); | |
// Thanks for the help @yanncabon && @vancematthews! | |
var solution = data.filter(function(d) { | |
if (d.name && d.name.length) { | |
return d.name; | |
} | |
}) | |
.map(function(d) { | |
return d.name; | |
}); |
You would prefer
var solution = data.filter(function(d) {
return d.name && d.name.length;
})
.map(function(d) {
return d.name;
});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👍