Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking for an array in an multidimensional array (pref-jQuery)

I've got a multi-dimensional array, and I'm trying to check if it holds another array. I'm using jQuery.inArray function at the moment (I was trying Array.prototype but kept getting errors, never used that before).

I am trying to ensure that my parent array doesn't add the same child array twice

if(jQuery.inArray(new Array(step[0],step[1],r2),unavailArray)==-1){
    alert(jQuery.inArray(new Array(step[0],step[1],r2),unavailArray));

    unavailArray.push(new Array(step[0],step[1],r2));
  }

I've also tried

jQuery.inArray("[step[0],step[1],r2]",unavailArray)==-1

and

jQuery.inArray([step[0],step[1],r2],unavailArray)==-1

they all return -1, and when I look at the array, I have

[[630,690,09],[3180,3220,2],[3180,3220,2]]

so clearly something isn't working.

like image 255
pedalpete Avatar asked Jan 01 '26 08:01

pedalpete


1 Answers

I believe you're issue is that you keep adding new Array() for the arrays instead of giving them a variable name to point back to, hence they're never really the same even though they may have the same exact content as each other.

For this to work as you wish you need to assign new Array([step[0],step[1],r2]) to a variable and check that variable instead of new Array()

var blah = new Array(step[0],step[1],r2);

// this will add the array to unavailArray
if(jQuery.inArray(blah,unavailArray)==-1){
    alert(jQuery.inArray(blah,unavailArray));

    unavailArray.push(blah);
  }else{
    alert('found so was not added');
}

// Try again and it wont, instead firing off the alert message
if(jQuery.inArray(blah,unavailArray)==-1){
    alert(jQuery.inArray(blah,unavailArray));

    unavailArray.push(blah);
  }else{
    alert('found so was not added');
}

Here is a link to a JSFiddle I made to illustrate this: Live Example

like image 109
subhaze Avatar answered Jan 03 '26 22:01

subhaze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!