Robert Robert - 4 months ago 10
jQuery Question

Checking for duplicate nested arrays

I have an array that will be populated with information each time the user clicks a button. The information being pushed to this array is within an array itself. so something along the lines of this:

var parentArray = [];
var childArray = ["Info1", "Info2", 500];

$("#button").on("click", function(){
parentArray.push(childArray);
})


Each time the user clicks the button, the
childArray
will have different information based on a different user input. For example, the user clicks on one point on a map, the
childArray
takes certain information into it. The user clicks on a different point on the map and the
childArray
takes certain information into it. Each time the
childArray
will be different or the same. the user then clicks the button and the information in the
childArray
is pushed to the
parentArray
.

My issue is, I want to get rid of duplicate
childArrays
from within the
parentArray
. So, say one
childArray
looks like this:

["Info1", "Info2", 25]


Another child array looks like this:
["Info1", "Info2", 50]


And another looks like this:
["Info1", "Info2", 25]


I want to find if two
childArrays
are the same, the first and third arrays, and if they are, remove all but one similar array so in the end, instead of looking like this:

[["Info1", "Info2", 25], ["Info1", "Info2", 50], ["Info1", "Info2", 25]]


my
parentArray
would look like this:

[["Info1", "Info2", 25], ["Info1", "Info2", 50]]


Is it possible to achieve this? If so, how would I go about doing it?

I hope this made sense.

Answer

You could use filter() and thisArg parameter

var ar = [["Info1", "Info2", 25], ["Info1", "Info2", 50], ["Info1", "Info2", 25]];
var result = ar.filter(function(e) {
  if(!this[e.join('|')]) {
    this[e.join('|')] = true;
    return e;
  }
}, {});

console.log(result);