0

Lets say I have 2 arrays:

var a = [];
var b = [];

a.push({id:1, name:"Joe"});
a.push({id:2, name:"Jeff"});
a.push({id:3, name:"John"});

Is there a quick way to populate b with just a's names in Javascript, or do I have to use a loop?

E.g, something like:

b = a[].name;    // b is now ["Joe","Jeff","John"]
0

6 Answers 6

3

A loop must be used in some form. Either by your code or by a function you call to do the copy of specific elements. The solution using say map still uses a loop under the hood

for (var i = 0; i < a.length; i++) {
  b.push(a[i].name);
}
Sign up to request clarification or add additional context in comments.

Comments

2

With jQuery you can say:

var b = $.map(a, function(val, i) { return val.name; });

jQuery's $.map() method is equivalent to JavaScript's own Array.map() method, except the latter is a relatively new feature of JS and so doesn't work in older browsers (i.e., pre-IE9).

2 Comments

I like this solution better than a loop, we're using jQuery and I def. prefer a convenience function over having to write another g-damned loop
Cool. Obviously if you had some code that needed to be ultra-efficient you'd write your own loop to save all the function calls, but for "normal" cases it's much nicer to let .map() hide the looping from you.
2

If you don't care about older browsers you can use the ES5 map method:

b = a.map(function(elem) {
    return elem.name;
});

If you do care about older browsers, you can polyfill the map method (MDN provides a decent polyfill) or you can use a normal loop, as you suggest (although obviously the map method uses some form of loop anyway).

Comments

0

You would have to loop. There are various collections manipulation functions now baked into the language. One if them that would be useful here is map.

var b = a.map(function(person) {
    return person.name;
});

Checkout the Underscore.js library that makes a lot of operations like this easy. It has a method named pluck that would be ideal here.

var b = _.pluck(a, 'name');

Comments

0

You would need to iterate through a in order to produce a new array in b with each name.

Comments

0

It requires a loop, but there are library functions that can abstract the looping away for you. I'm partial to using Underscore.js for these types of things (and I generally get it for free since I use Backbone liberally) but you can find similar functions in JQuery such as $.map

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.