Skip to content Skip to sidebar Skip to footer

Pushing Unique Jquery Objects To An Array

I'm completely new to using Jquery, and I'm trying push unique objects to an array, and if the object is already in the array, it removes them. This is for students to book multipl

Solution 1:

From your comment:

the object is being created on every single click

That's the problem: Equivalent objects are not either == or === to each other, and inArray uses === to find the object. For instance, $.inArray({id:1}, [{id:1}]) returns -1:

console.log($.inArray({id:1}, [{id:1}])); // -1
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

So you'll want to use something else. On modern browsers, you can use Array#findIndex and use a predicate function:

var index = array.findIndex(function(e) { return e.id == id && e.id2 == id2; });

Example:

var array = [];
run(1, 1); // addsrun(1, 2); // addsrun(1, 1); // removesconsole.log(array); // ends up with just the 1,2 object in itfunctionrun(id, id2) {
  // Find the equivalent object if anyvar index = array.findIndex(function(e) { return e.id == id && e.id2 == id2; });
  
  // Found?if (index == -1) {
    // No, add one
    array.push({id: id, id2: id2});
  } else {
    // Yes, remove it
    array.splice(index, 1);
  }
}

Array#findIndex can be shimmed/polyfilled on older browsers; MDN has a polyfill here(I've also quoted it below, just in case, but I can't imagine MDN disappearing any time soon).


Side note: It's a bit more concise with ES2015 (aka "ES6") (browsers aren't quite ready for us to use ES2015 in the wild yet, but you can transpile):

let index = array.findIndex(e => e.id == id && e.id2 == id2);

Here's MDN's polyfill as of this writing (25/05/2016):

if (!Array.prototype.findIndex) {
  Array.prototype.findIndex = function(predicate) {
    if (this === null) {
      thrownewTypeError('Array.prototype.findIndex called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      thrownewTypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return i;
      }
    }
    return -1;
  };
}

Solution 2:

In your situation, I suggest that you should take a look on LINQ JS

Example:

var exObjArr = Enumerable.From(array)
                   .Where(function(x){return x.id1 == object.id1 && x.id2 == object.id2})
                   .ToArray();

if(exObjArr.length == 0){
     //object does not exist
} else{
     //object exists
}

Post a Comment for "Pushing Unique Jquery Objects To An Array"