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

85
Views
Filter array values before loop

I have one array with the same ids of my div data-id: i need to do a loop for my array only for values without the class ".empty-box". In this case I need to cicle my array with value id 1, 2 and 3 because 4 and 5 have the same value of the div empty-box.

<div class="box" data-id="1"> </div>
<div class="box" data-id="2"> </div>
<div class="box" data-id="3"> </div>
<div class="box empty-box" data-id="4"> </div>
<div class="box empty-box" data-id="5"> </div>
var emptyBoxes = $('.empty-box')
var myArray = [
  {id:1},
  {id:2},
  {id:3},
  {id:4},
  {id:5}
]

My solution look like this, but I'm not sure is the best way:

var myArray = [
  {id:1},
  {id:2},
  {id:3},
  {id:4},
  {id:5}
]

var emptyBoxes = $('.empty-box');

var ids = [];

emptyBoxes.each(function(i, v){
    ids.push($(v).data('id'));
})

var list = myArray.filter(function(el) {return !ids.includes(el.id)};

Have you got any solution?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

With jQuery, you have access to the :not selector.

const nonEmptyBoxes = $('.box:not(.empty-box)');
about 4 years ago · Juan Pablo Isaza Report

0

You could use document.querySelectorAll('div.box[data-id]:not(.empty-box)') to get all the boxes that aren´t empty and have an id.

I´ve added an Example to show the speed difference.

var myArray = [
  {id:1},
  {id:2},
  {id:3},
  {id:4},
  {id:5}
]
console.time('old');
var emptyBoxes = $('.empty-box');

var ids = [];

emptyBoxes.each(function(i, v){
    ids.push($(v).data('id'));
})

var list = myArray.filter(function(el) {return !ids.includes(el.id)});
console.log(list);
console.timeEnd('old');
console.time('new');
const validBoxes = document.querySelectorAll('div.box[data-id]:not(.empty-box)');
let newList = [];
validBoxes.forEach((element) => {newList.push({id: element.getAttribute('data-id')})});
console.log(newList);
console.timeEnd('new');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box" data-id="1"> </div>
<div class="box" data-id="2"> </div>
<div class="box" data-id="3"> </div>
<div class="box empty-box" data-id="4"> </div>
<div class="box empty-box" data-id="5"> </div>

about 4 years ago · Juan Pablo Isaza 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!