Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

javascript - How to check if an array contains another array?

I needed 2d arrays, so I made a nested array since JavaScript doesn't allow them.

They look like this:

var myArray = [
  [1, 0],
  [1, 1],
  [1, 3],
  [2, 4]
]

How can I check if this array includes a specific element (i.e. one of these [0,1] arrays) in vanilla JS?

Here is what I tried, with no success (everything returns false) (EDIT: I included the answers in the snippet):

var myArray = [
  [1, 0],
  [1, 1],
  [1, 3],
  [2, 4]
]

var itemTrue = [2, 4];
var itemFalse = [4, 4];

function contains(a, obj) {
  var i = a.length;
  while (i--) {
    if (a[i] === obj) {
      return true;
    }
  }
  return false;
}

// EDIT: first answer's solution

function isArrayInArray(x, check) {
  for (var i = 0, len = x.length; i < len; i++) {
    if (x[i][0] === check[0] && x[i][1] === check[1]) {
      return true;
    }
  }
  return false;
}

// EDIT: accepted answer's solution


function isArrayInArray2(x, check) {
  var result = x.find(function(ele) {
    return (JSON.stringify(ele) === JSON.stringify(check));
  }) 
  return result !=null
}

console.log("true :" + myArray.includes(itemTrue));
console.log("false :" + myArray.includes(itemFalse));

console.log("true :" + (myArray.indexOf(itemTrue) != -1));
console.log("false :" + (myArray.indexOf(itemFalse) != -1));

console.log("true :" + contains(myArray, itemTrue));
console.log("false :" + contains(myArray, itemFalse));

// EDIT: first answer's solution
console.log("true :" + isArrayInArray(myArray, itemTrue));
console.log("false :" + isArrayInArray(myArray, itemFalse));


// EDIT: accepted answer's solution
console.log("true :" + isArrayInArray2(myArray, itemTrue));
console.log("false :" + isArrayInArray2(myArray, itemFalse));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Short and easy, stringify the array and compare as strings

function isArrayInArray(arr, item){
  var item_as_string = JSON.stringify(item);

  var contains = arr.some(function(ele){
    return JSON.stringify(ele) === item_as_string;
  });
  return contains;
}

var myArray = [
  [1, 0],
  [1, 1],
  [1, 3],
  [2, 4]
]
var item = [1, 0]

console.log(isArrayInArray(myArray, item));  // Print true if found

check some documentation here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...