Tengda Su
Tengda Su

Reputation: 153

JavaScript indexOf didn't return good results

I'am trying to find the index of my array by the function indexOf, but I can't get a right result.

var points =[
    ["2.408","38.8"],
    ["2.410","38.8"],
    ["2.410","38.76"]
];
var position = points.indexOf(["2.408","38.8"]);

I think it should return 0 rather than -1, so I campared the two array like blow.

console.log(points[0]===["2.408","38.8"])

Then I got false.

I don't understand why it's not the true.

I'll appreciate for your suggestion...

Upvotes: 2

Views: 79

Answers (3)

Pac0
Pac0

Reputation: 23129

You can use findIndex and a helper function to create a comparison to any array.

    var allElementsEquals = function(refArray) {
        return function(array) {
          if (array.length !== refArray.length) return false;
    	  for (var i = 0; i < array.length; i++) { if (array[i] !== refArray[i]) return false; }
          return true
        }
    }

    // test 1 
    var points =[
        ["2.408","38.8"],
        ["2.410","38.8"],
        ["2.410","38.76"]
    ];
    var position = points.findIndex(allElementsEquals(["2.408","38.8"]));
    console.log(position);


    // test 2
    var points =[
        ["2.410","38.8"],
        ["2.408","38.8"],
        ["2.410","38.76"]
    ];
    var position = points.findIndex(allElementsEquals(["2.408","38.8"]));
    console.log(position);
    
    // test 3
        var points =[
        ["2.410","38.8"],
        ["2.409","38.8"],
        ["2.410","38.76"]
    ];
    var position = points.findIndex(allElementsEquals(["2.408","38.8"]));
    console.log(position);

    // test 4
        var points =[
        ["2.410","38.8"],
        ["38.8","2.408"],
        ["2.410","38.76"]
    ];
    var position = points.findIndex(allElementsEquals(["2.408","38.8"]));
    console.log(position);

Upvotes: 0

zero298
zero298

Reputation: 26867

You are not searching for the same Array.

When you create an Array, you are creating an Object and storing a reference to it in a variable. When you search the Array of Arrays, the find logic will be comparing by reference, not by deep value. That's why the indexOf is giving you -1; you aren't actually searching for anything that is really in the Array of Arrays.

const a = ["foo", "bar"],
  b = ["foo", "bar"];

const arr = [a];

console.log(arr.indexOf(["foo", "bar"])); // -1, not the right reference
console.log(arr.indexOf(b)); // -1, again, not the right reference
console.log(arr.indexOf(a)); // 0, the right reference

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122027

You can do this with findIndex and every methods.

var points = [["2.408", "38.8"], ["2.410", "38.8"],["2.410", "38.76"]];
const arr = ["2.408","38.8"];

const i = points.findIndex(a => {
  return a.length == arr.length && arr.every((e, i) => a[i] == e)
})

console.log(i)

Upvotes: 2

Related Questions