Rebecca O'Riordan
Rebecca O'Riordan

Reputation: 883

How to push values from .each() to one array in jQuery?

I have this:

$(".section").each( function() {
    var x = $(this).attr('data-test');
    var y =[];
    y.push(x);
});

I will get 10 values for data-test, and I want to push them to the array 'y' to be like this:

['1','2','3','4','5','6'...'10']

How do I "split up" x into each of its values and push them to y?

EDIT:

HTML e.g:

<li class="section" data-test="15"></li>
<li class="section" data-test="6"></li>
<li class="section" data-test="78"></li>

and so on

Upvotes: 0

Views: 60

Answers (3)

Sterling Archer
Sterling Archer

Reputation: 22445

Obligatory vanilla answer using ES6

var y = [];
Array.from(document.querySelectorAll(".section")).forEach(x => {
    y.push(x.getAttribute("data-test"))
});

The issue you're running into is you're resetting the array y upon each iteration, thus removing previous indexes.

Array.from() converts the NodeList returned from querySelectorAll into a nicer iterable, (you can also use map instead of forEach) then simply push the data attribute of x into the array

Upvotes: 2

guest271314
guest271314

Reputation: 1

$.merge() could be used to concatenate items to an array

var y = [];

$(".section").each(function() {
  $.merge(y, [$(this).data("test")])
});

console.log(y)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li class="section" data-test="15"></li>
<li class="section" data-test="6"></li>
<li class="section" data-test="78"></li>

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337743

Given your HTML sample you can use map() to create the array for you:

var y = $(".section").map(function() {
    return $(this).data('test');
}).get();

// This is only for display purposes
$('div').text(JSON.stringify(y)); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="section" data-test="15">15</li>
  <li class="section" data-test="6">6</li>
  <li class="section" data-test="78">78</li>
</ul>

<div></div>

Upvotes: 7

Related Questions