0

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?

2 Answers 2

1

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

const nonEmptyBoxes = $('.box:not(.empty-box)');
Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.