最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to check if a multidimensional array has a specific array? - Stack Overflow

programmeradmin1浏览0评论

How to check if arrays has array?

var arrays = [[1, 1], [2, 2]];
var array = [1,1];

[1, 1] === [1, 1]; // false
arrays.includes(array); // false
arrays.indexOf(array); // -1

How to check if arrays has array?

var arrays = [[1, 1], [2, 2]];
var array = [1,1];

[1, 1] === [1, 1]; // false
arrays.includes(array); // false
arrays.indexOf(array); // -1
Share Improve this question edited Dec 25, 2021 at 23:00 Leau 1,0747 silver badges19 bronze badges asked Mar 26, 2013 at 0:45 TukkanTukkan 1,6253 gold badges20 silver badges34 bronze badges 2
  • 2 This really helps. stackoverflow./questions/12604062/… – Near Commented Mar 26, 2013 at 0:53
  • 1 It returns -1 because b isn't in a. [1, 1] == [1, 1] is false in JavaScript. – Blender Commented Mar 26, 2013 at 0:54
Add a ment  | 

3 Answers 3

Reset to default 4

indexOf pares using strict equality (===). Your elements would have to be the exact same object.

so

var a = [1,1];

var b = [a,[1,2]];

b.indexOf(a)// 0

because a === a

but

b.indexOf([1,1])// -1

because [1,1] is a different object than a so they're not strictly equal.

MDN Docs

To do what you want to do you'll need to do something more involved. You can loop over the values and use something like whats in this question's answers to do the parison

indexOf returns -1 if it does not find a match in the array. Your array a does not contain element b.

EDIT:

To clarify on what @JonathanLonowski said, the reason there is not a match is because you are doing a strict parison, paring the references, not the values.

<Array>.some method tests whether at least one array in the multi-dimensional array passes the test implemented by the provided function.

<Array>.every method tests whether all array items in the array pass the test implemented by the provided function.

These two methods bined make it possible to check if all the items of an array in the multidimensional one are worth those of that sought.

const checkArray = (arrays, array) => arrays.some(a => {
  return (a.length > array.length ? a : array).every((_, i) => a[i] === array[i]);
});

const arrays = [[0, 1], [2, 2], [0, 3, 2, 1]];

[
  [0, 1],          // true
  [2, 2],          // true
  [0, 3, 2, 1],    // true
  [1, 0, 3, 2, 1], // false
  [2, 2, 1],       // false
  [0, 0],          // false
  [1, 2],          // false
  [0, 1, 2]        // false
].forEach(array => {
  console.log(checkArray(arrays, array));
});

发布评论

评论列表(0)

  1. 暂无评论