lm.
lm.

Reputation: 4311

Get values of specific property of array elements in Javascript

I have following question on Javascript Suppose we have srcArr - array of objects , each defined as following

var srcElement = {id:id_val , prop1:value1, prop2:value2}

I need to get array of id-s of array elements.I.e. array of elements like {id;:id_val} The simplest way is something like this

var arrayLength = srcArr.length;
for (var index=0; index<arrayLength;index++) {
  idsArr.push(srcArr[index].id);     
}

The question is : Is there more effective way to get ids of array elements?
Thanks in advance

Upvotes: 0

Views: 68

Answers (4)

user1636522
user1636522

Reputation:

If effective means short and readable, you could use the Lodash pluck function :

var idsArr = _.pluck(srcArr, 'id');

http://lodash.com/docs#pluck

Here is the souce code : https://github.com/lodash/lodash/blob/2.4.1/dist/lodash.compat.js#L3848. I suspect it to be slower than a good old for loop but you should run some performance tests if you actually care about that : google "jsperf map".

That said, it's quite easy to write your own pluck function :

function pluck(src, key) {
    var i = 0, l = src.length, result = [];
    while (i < l) result.push(src[i++][key]);
    return result;
}

Upvotes: 0

roo2
roo2

Reputation: 6071

using underscore.js's map function

srcArr = [{id:1}, {id:2}]
var result = _.map(srcArr, function(el){
    return el.id
});
//result = [1,2]

map will perform the same function on each element and add the result to a new array

EDIT: this is not as fast as a native for loop.

http://jsperf.com/javascript-map-vs-jquery-map-vs-jquery-each

Upvotes: 1

Vishal Suthar
Vishal Suthar

Reputation: 17194

The map method can be used as an iterator, but is really meant to manipulate the supplied array and return a new array.

So at the end:

For loop map is much more faster than Jquery map. Test the performance of the same here

Here you go:

var srcArray = [{
    id: 1,
    prop1: 'a',
    prop2: 'b'
}, {
    id: 2,
    prop1: 'c',
    prop2: 'd'
}];
map = function (array, mapFunction) {
    var newArray = new Array(array.length);
    for (var i = 0; i < array.length; i++) {
        newArray[i] = mapFunction(array[i]);
    }

    return newArray;
}
var newItems = map(srcArray, function (i) {
    return i.id;
});

Output

newItems: [1,2]

Live Demo

enter image description here

Upvotes: 1

elclanrs
elclanrs

Reputation: 94101

A common re-usable functional approach:

var collec = [
  {num:1, str:'a'},
  {num:2, str:'b'}
];

var dot = function(prop) {
  return function(obj) {
    return obj[prop];
  }
};

collec.map(dot('num')); //=> [1,2]
collec.map(dot('str')); //=> ['a','b']

Upvotes: 2

Related Questions