[JS practice] Pluck function(读取数组中相同属性的项目)

Title :
Pluck (读取数组中相同属性的项目)

Description:

Implement pluck, which takes an array of objects and a property name, and returns an array containing the named property of each object.

实现一个pluck方法,输入的参数为一个包含N个对象的数组和一个字符串,输出数组中包含的字符串所对应的对象的值,如果没有则返回undefined。
我用到了循环,不过似乎还有更简单的方法哦 🙂

For example:

pluck([{a:1}, {a:2}], 'a') // -> [1,2]

If an object is missing the property, you should just leave it as undefined in the output array.

Normal solution :

function pluck(objs, name) {
  var rtArr = [];
  if(name == "" || objs.length == 0) {
    return rtArr;
  }
  objs.forEach(function(o){
    rtArr.push(o[name]);
  });
  return rtArr; 
}

Best solution :

function pluck(objs, name) {
  return objs.map(function(obj) { return obj[name] });
}

Ref. from codewars

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s