// Write a function that returns an array of only the objects with truthy values
// for the passed in key.
//
// pluckTruthy({a: 1, b: '', c: false}, 'a') => [1]
// pluckTruthy({a: 1, b: '', c: false}, 'b') => []
// pluckTruthy({a: 1, b: '', c: false}, 'c') => []
// pluckTruthy({a: 1, b: '', c: false}, 'd') => []
//
function pluckTruthy(obj, key) {
var result = [];
for (var i = 0; i < obj.length; i++) {
if (obj[i][key]) {
result.push(obj[i][key]);
}
}
return result;
}
// console.log(pluckTruthy({a: 1, b: '', c: false}, 'a'));
Example 1:
<script type="text/javascript">
var list = [{name: 'jack', age: 14}, {name: 'jill', age: 15},
{name: 'humpty', age: 16}];
console.log(_.pluck(list, 'age'));
</script>
Example 2:
<script type="text/javascript">
var goal = [
{
"category" : "other",
"title" : "harry University",
"value" : 50000,
"id":"1"
},
{
"category" : "traveling",
"title" : "tommy University",
"value" : 50000,
"id":"2"
},
{
"category" : "education",
"title" : "jerry University",
"value" : 50000,
"id":"3"
},
{
"category" : "business",
"title" : "Charlie University",
"value" : 50000,
"id":"4"
}
]
console.log(_.pluck(goal, 'category'));
</script>