Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

javascript pluck

// 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'));
 
PREVIOUS NEXT
Tagged: #javascript #pluck
ADD COMMENT
Topic
Name
9+2 =