Difference between Arrays

Asked

Viewed 929 times

0

I have a question in a code:

I got 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, but without success,:

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

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

  • Your code is correct... (https://jsfiddle.net/9kjz7b16/) What’s the problem?

2 answers

1

You can also use the includes:

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

EDIT:

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

  • 1

    It is worth remembering that the includes is still experimental and not suitable for use in production. The alternative solution would be leiturasRealizadas.indexOf(x) < 0

  • Thanks for the remark. I edited my reply to add this point

0

Try it this way:

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 is equal to -1 and if $.inArray(item, milksRealized) returns -1, you know that the value in the original matrix is not in the exclusion matrix, so you keep it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.