Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

171
Views
Split list of elements into groups

I would like to split list of elements into groups of 4 except one before last that should contain 2 elements only.

x x x x x x x
x x x x x x x
x x x x x    x
x x x x x    x

This will slice into groups of 4 el.:

for ( var i = 0; i < $(".el").length; i+=4 ) {
  $(".el").slice(i, i + 4).wrapAll('<div class="group">');
}

https://jsfiddle.net/p13rcd1c/

What is an approach to make one group to contain only 2 elements?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

By calculating the number of groups beforehand, the slice could be adapted if the 'group'-index is the one before last:

var els = $(".el"),grp = 4, cnt = Math.ceil(els.length/grp), rem = els.length % grp, ind = 0;
for(var i = 0; i <= cnt;i++) {
    els.slice(ind, ind += (i==cnt-2 ? rem : grp)).wrapAll('<div class="group">');
}

edit: an alternate version if the total amount can deviate from filling out. This version fills the last group with 4, but fills the one before that with the remainder. (If that is not the intention, and the original code was the required goal, the linked fiddle still contains the original)

var els = $(".el"),grp = 4, cnt = Math.ceil(els.length/grp), rem = els.length % grp, ind = 0;
for(var i = 0; i <= cnt;i++) {
els.slice(ind, ind += (i==cnt-2 ? rem : grp)).wrapAll('<div class="group">');
}
* { margin: 0; padding: 0}

body {
  margin: 10px
}

.el {
  width: 20px;
  height: 10px;
  margin-bottom: 2px;
  background-color: blue;
}

.group {
  float: left;
  margin-left: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>

fiddle

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!