rhughes
rhughes

Reputation: 9583

Returning an array of values

I need to get a list of values from a set of element attributes and store them in an array.

Currently, I am doing this:

var ids = [];

$("my selector").each(function (idx, v) {

    ids.push($(v).data("id"));
});

This seems a bit clunky. Is there a more efficient/streamlined way of doing this? Perhaps something more like this:

var ids = $("my selector").data("id");

Upvotes: 0

Views: 49

Answers (2)

Amit Joki
Amit Joki

Reputation: 59242

Less clunky:

$("my selector").each(function () {
    ids.push($(this).data("id"));
});

By, removing idx and v, you can use $(this)

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Try using .map() along with .get() in this context,

var ids = $("my selector").map(function(){
   return $(this).data("id");
}).get();

Upvotes: 6

Related Questions