Michael Parker
Michael Parker

Reputation: 12966

Better way to create arrays in javascript?

I'm trying to create an array in Javascript with a size that is equivalent to the number of times a certain class is found in the DOM, and then iterate through it to grab the text from an input field present in that class. I can easily do this like so:

var count = 0;
$('.className').each(function() {
    count++;
});
var classes = new Array(count);
count = 0;
$('.className input[type=text]').each(function() {
    classes[count++] = $(this).val();
});

This looks like a lot of code for what seems to be a relatively simple task. Is there a more efficient or less lengthy way of doing this?

Thanks

Upvotes: 0

Views: 55

Answers (5)

War10ck
War10ck

Reputation: 12508

Arrays are dynamic and therefore don't need to be initialized. Create a new array, loop through the inputs and push the values to the new array:

var classes = [];
$('.className input[type=text]').each(function(idx, elem) {
    classes.push($(elem).val());
});

Upvotes: 0

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51330

Use jQuery's map function, then get if you need a pure array:

var values = $('.className input[type=text]').map(function() {
    return $(this).val();
}).get();

Upvotes: 2

ColinE
ColinE

Reputation: 70142

You can construct an array of elements directly from your selector via the makeArray function, then transform the result using a map.

var classes = $.makeArray($('.className input[type=text]')).map(function() {
    return $(this).val();
});

Upvotes: 3

Igor
Igor

Reputation: 33993

each passes the index, so you don't need to do it yourself:

var classes = [];
$('.className input[type=text]').each(function(index, value) {
    classes[index] = $(this).val();
});

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382150

It looks like you want this :

var classes = $('.className input[type=text]').map(function(){
    return this.value
}).get();

But it's a guess : it's not clear why you start by counting all elements of the class and then iterate on the inputs.

Upvotes: 6

Related Questions