1

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.

1 Answers1

0

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);
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • Sorry, I saw what I did wrong in regards to my first comment. Can you explain why you have a separate set of curly brackets and why it actually makes it work? –  Aug 02 '16 at 12:25
  • 1
    That is object as `thisArg` parameter or `this` in function. – Nenad Vracar Aug 02 '16 at 12:26
  • Ah, ok. So it just creates an empty object when the filter method completes? –  Aug 02 '16 at 12:29
  • 1
    Not really, it adds your element (as string) - `this[e.join()]` as `this` object key and set it to true or whatever if there isn't property with same key already in `this` object and returns it. If there was same object in array already or same key of `this` filter doesn't return it. https://jsfiddle.net/Lg0wyt9u/1081/ – Nenad Vracar Aug 02 '16 at 12:34
  • You are doing this just check is `this` https://jsfiddle.net/Lg0wyt9u/1083/ – Nenad Vracar Aug 02 '16 at 12:42