Skip to content

Instantly share code, notes, and snippets.

@jczaplew
Last active August 29, 2015 14:04
Show Gist options
  • Save jczaplew/1bdfd9802d84c7d678a9 to your computer and use it in GitHub Desktop.
Save jczaplew/1bdfd9802d84c7d678a9 to your computer and use it in GitHub Desktop.
Array.map confusion
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;
});
@mapsam
Copy link

mapsam commented Jul 31, 2014

👍

@ycabon
Copy link

ycabon commented Jul 31, 2014

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