Home > Net >  Filter array values before loop
Filter array values before loop

Time:10-26

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($ls(v).data('id'));
})

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

Have you got any solution?

CodePudding user response:

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

const nonEmptyBoxes = $('.box:not(.empty-box)');

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related