pluck.js (2404B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var isArray = require( '@stdlib/assert/is-array' ); 24 var copy = require( './../../copy' ); 25 var hasOwnProp = require( '@stdlib/assert/has-own-property' ); 26 var defaults = require( './defaults.json' ); 27 var validate = require( './validate.js' ); 28 29 30 // MAIN // 31 32 /** 33 * Extracts a property value from each element of an object array. 34 * 35 * @param {Array} arr - source array 36 * @param {*} prop - property to access 37 * @param {Options} [options] - function options 38 * @param {boolean} [options.copy=true] - boolean indicating whether to return a new data structure 39 * @throws {TypeError} first argument must be an object array 40 * @throws {TypeError} options argument must be an object 41 * @throws {TypeError} must provide valid options 42 * @returns {Array} destination array 43 * 44 * @example 45 * var arr = [ 46 * { 'a': 1, 'b': 2 }, 47 * { 'a': 0.5, 'b': 3 } 48 * ]; 49 * 50 * var out = pluck( arr, 'a' ); 51 * // returns [ 1, 0.5 ] 52 * 53 * @example 54 * var arr = [ 55 * { 'a': 1, 'b': 2 }, 56 * { 'a': 0.5, 'b': 3 } 57 * ]; 58 * 59 * var out = pluck( arr, 'a', {'copy':false} ); 60 * // returns [ 1, 0.5 ] 61 * 62 * var bool = ( arr[ 0 ] === out[ 0 ] ); 63 * // returns true 64 */ 65 function pluck( arr, prop, options ) { 66 var opts; 67 var out; 68 var err; 69 var v; 70 var i; 71 72 if ( !isArray( arr ) ) { 73 throw new TypeError( 'invalid argument. First argument must be an array. Value: `' + arr + '`.' ); 74 } 75 opts = copy( defaults ); 76 if ( arguments.length > 2 ) { 77 err = validate( opts, options ); 78 if ( err ) { 79 throw err; 80 } 81 } 82 if ( opts.copy ) { 83 out = new Array( arr.length ); 84 } else { 85 out = arr; 86 } 87 for ( i = 0; i < arr.length; i++ ) { 88 v = arr[ i ]; 89 if ( 90 v !== void 0 && 91 v !== null && 92 hasOwnProp( v, prop ) 93 ) { 94 out[ i ] = v[ prop ]; 95 } 96 } 97 return out; 98 } 99 100 101 // EXPORTS // 102 103 module.exports = pluck;