Difference between Arrays

0

I have a question in a code:

I have these two arrays:

var listaLeituras= [12,13,14,15,16,17,18];<br>
var leiturasRealizadas = [12,15,18];

In the end, I needed a code to show in a third array the unrealized readings, which would be the numbers 13,14,16,17. I tried the code below, however, without success:

var leiturasIgnoradas = listaLeituras.filter(function(leitura) {<br>
  return leiturasRealizadas.indexOf(leitura) < 0;<br>
});

NOTE: My application is based on pure Javascript and can not use external libraries.

    
asked by anonymous 05.08.2017 / 20:11

2 answers

0

Try this:

var listaLeituras= [12,13,14,15,16,17,18];
var leiturasRealizadas = [12,15,18];

var leiturasIgnoradas = listaLeituras.filter(function(item) {
    return !~$.inArray(item, leiturasRealizadas);
});

console.log(leiturasIgnoradas);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>

!~ It is a shortcut to see if a value equals -1 and if $ .inArray (item, ReadRequested) returns -1, you know that the value in the original array is not in the delete array, so you keep it.

    
05.08.2017 / 20:26
0

You can also use includes :

listaLeituras.filter(x => !leiturasRealizadas.includes(x));

EDIT:

As mentioned by Anderson Carlos Woss , includes is experimental for ES7 and may be subject to change. It is recommended to look at the documentation to check compatibility.     

05.08.2017 / 23:57