var sample = [
  [0, 0],
  [0, 1],
  [0, 2]

Given an array of, is [0, 0] in this array? I want to know how to search for.

var sample1 = [1, 2, 3, 4];
sample1.includes(1) //=>true is returned

I knew that, so I thought it could be used in this case,

sample.includes([0, 0]);//=>false is returned.

As a result, I thought that the difference between passing by value and passing by reference was the cause,
I couldn't find it.

If anyone knows how to search the contents of a multidimensional array, I would appreciate it if you could tell me.

  • Answer # 1

    The way to search for [0,0] in the array is to write a predicate in the find method of the array.

    [[0,0],[0,1]].find(function(x){return Array.isArray(x)&&x.length == 2&&x[0] == 0&&x[1] == 0})
    ← Array [0, 0]
    [[1,1],[0,1]].find(function(x){return Array.isArray(x)&&x.length == 2&&x[0] == 0&&x[1] == 0})
    ← undefined

    If you need a predicate to search an array, you may add the following user function to the Array class.

    Array.isEqualTo = function(x){return function(y){if (!Array.isArray(y) || y.length != x.length) return false;for (let i = 0;i<x.length ;i++) {if (x[i] != y[i]) return false;} return true;}}

    The usage is like this.

    ← undefined
    ← Array(3) [1, 2, 3]

  • Answer # 2

    I thought it was due to the difference between passing by value and passing by reference

    Yes, that's right.
    Arrays with the same reference, such asArray.prototype.includes()Is passed as an argument, the return value will betrueWill be.

    var sample = [
      [0, 0],
      [0, 1],
      [0, 2]
    var target = sample[0];
    sample.includes(target);// true

    I think boniri wants to find out whether all the elements contained in one array are contained in another array in the same order without excess or deficiency, but this is achieved with one method. I can not do it.

    The implementation changes depending on the detailed conditions, but this time I implemented the demo with the following requirements.

    The search source array must be a two-dimensional array (array array)

    All elements of each array at the end must be numbers

    Detailed comments are written in the source code.


    Reference material

    Documents related to Array.isArray()

    Documentation about Array.prototype.some()

    Documentation about Array.prototype.every()

Related articles