Krystian
Krystian

Reputation: 458

comparing two dimensional array js

I am coding something in JS and I have to test code - I have to check if elements in 2 arrays are the same. So I've got an array: boreholes = [[66000, 457000],[1111,2222]....]; and I want to check if this array contain element for eg. [66000,457000] so I did: boreholes.indexOf([66000,457000]) but it returns -1, so I iterate trough array by:

for (var i = 0; i< boreholes.length; i++){
 if (boreholes[i] == [66000, 457000]){
  console.log('ok');
  break;
 }
};

but still I've got nothing. Can someone explain me what am I doing wrong?

Upvotes: 0

Views: 4216

Answers (5)

webdeb
webdeb

Reputation: 13211

Currently I had the same problem, did it with the toString() method

var array1 = [1,2,3,[1,2,3]]
var array2 = [1,2,3,[1,2,3]]

array1 == array2 // false
array1.toString() == array2.toString() // true

var array3 = [1,2,3,[1,3,2]]

// Take attention
array1.toString() == array3.toString() // false

Upvotes: 2

Vishal
Vishal

Reputation: 1234

You cannot compare arrays like array1 == array2 in javascript like you're trying to do here.

Here is a kludge method to compare two arrays:

function isEqual(array1, array2){
  return (array1.join('-') == array2.join('-'));
}

You can now use this method in your code like:

for (var i = 0; i< boreholes.length; i++){
 if (isEqual(boreholes[i], [66000, 457000]){
  console.log('ok');
  break;
 }
};

Upvotes: 3

Alex K
Alex K

Reputation: 7217

The question isn't quite clear if there can be more than 2 elements in an array, so this might work

var boreholes = [[66000, 457000],[1111,2222]]; 
var it = [66000, 457000];

function hasIt(boreholes, check) {
  var len = boreholes.length;
  for (var a = 0; a < len; a++) {
    if (boreholes[a][0] == check[0] && boreholes[a][1] == check[1]) {
       // ok
       return true;
    }
  }
  return false;
}

if (hasIt(boreholes, it)) {
  // ok, it has it
}

Upvotes: 0

Felix Gertz
Felix Gertz

Reputation: 175

You could also doing it with the Underscore.js-framework for functional programming.

function containsElements(elements) {
  _.find(boreholes, function(ele){ return _.isEqual(ele, elements); });
}

if(containsElements([66000, 457000])) {
  console.log('ok');
}

Upvotes: 0

Esailija
Esailija

Reputation: 140230

You are comparing distinct objects. When comparing objects, the comparison only evaluates to true when the 2 objects being compared are the same object. I.E

var a = [1,2,3];
var b = a;
a === b //true
b = [1,2,3];
a === b //false, b is not the same object

To compare arrays like this, you need to compare all of their elements separately:

for (var i = 0; i < boreholes.length; i++) {
    if (boreholes[i][0] == 66000 && boreholes[i][1] == 457000) {
        console.log('ok');
        break;
    }
}

Upvotes: 3

Related Questions