cucuru cucuru - 4 months ago 6
Javascript Question

inArray bidimensional doesnt work

I have a bidimensional array, and I'm trying to remove duplicates, I'm trying to do it with jquery function inArray.

This is my array:

var myArray = [ { data1 : "01" , data2 : "02" },
{ data1 : "01" , data2 : "03" },
{ data1 : "01" , data2 : "02" } ];
var newData = { data1 : "01" , data2 : "02" };

console.log($.inArray(newData, myArray));
-1


How can I compare this?

Answer

inArray:

Search for a specified value within an array and return its index (or -1 if not found).

Because you want to grep/search for objects the best method is always:

JSON.stringify(elementOfArray) == JSON.stringify(newData)

So, in jQuery you can filter or grep all elements with the same content:

var myArray = [{data1: "01", data2: "02"},
               {data1: "01", data2: "03"},
               {data1: "01", data2: "02"}];
var newData = {data1: "01", data2: "02"};

var result = $.grep(myArray, function (elementOfArray, indexInArray) {
  return JSON.stringify(elementOfArray) == JSON.stringify(newData);
});

console.log(result.length);


newData = {data1: "01", data2: "03"};
result = $.grep(myArray, function (elementOfArray, indexInArray) {
  return JSON.stringify(elementOfArray) == JSON.stringify(newData);
});

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