repl.it
JavaScript

Native implementation of Underscore pluck

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
map = function (collection, iteratee, context) {
  var result = [];

  if (Object.prototype.toString.call(collection) == '[object Object]') {
    for (var key in collection) {
      if (collection.hasOwnProperty(key)) {
        result.push(iteratee.call(context, collection[key], key, collection));
      }
    }
  } else {
    for (var i = 0; i < collection.length; i++) {
      result.push(iteratee.call(context, collection[i], i, collection));
    }
  }
  
  return result;
};

pluck = function (collection, propertyName) {
  return map(collection, function (value) {
    return value[propertyName];
  });
};


let metrics = [{app_id: 808238, app_name: 'App One', open_count: 400}, {app_id: 804562, app_name: 'App Two', open_count: 210}, {app_id: 902679, app_name: 'App Three', open_count: 3109}];

const appIds = pluck(metrics, 'app_id');
const appNames = pluck(metrics, 'app_name');
const openCounts= pluck(metrics, 'open_count');

console.log(appIds);
// => [ 808238, 804562, 902679 ]

console.log(appNames);
// => [ 'App One', 'App Two', 'App Three' ]

console.log(openCounts);
// => [ 400, 210, 3109 ]
Native Browser JavaScript