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

Check if an array of arrays contains a value in javascript - Stack Overflow

programmeradmin7浏览0评论

I know that if there is an array of values it must be used this approach:

console.log(['joe', 'jane', 'mary'].includes('jane')); // true

But in case of an array of arrays, is there a short way to do it? Without other putations between.

For this input:

[['jane'],['joe'],['mary']]

I know that if there is an array of values it must be used this approach:

console.log(['joe', 'jane', 'mary'].includes('jane')); // true

But in case of an array of arrays, is there a short way to do it? Without other putations between.

For this input:

[['jane'],['joe'],['mary']]
Share Improve this question asked Jun 1, 2021 at 9:45 Jean PierreJean Pierre 3211 gold badge9 silver badges24 bronze badges 1
  • 5 arr.some((a) => a.includes("jane")); – DecPK Commented Jun 1, 2021 at 9:47
Add a ment  | 

3 Answers 3

Reset to default 8

You can use flat method to flatten the array. For more neted array, you can also mention depth like flat(depth)

let arr = [["jane"],["joe"],["mary"]];

arr.flat().includes('jane'); //true

You can easily achieve this result using some

arr.some((a) => a.includes("jane"))

const arr = [
  ["jane"],
  ["joe"],
  ["mary"]
];
const arr2 = [
  ["joe"],
  ["mary"]
];

console.log(arr.some((a) => a.includes("jane")));
console.log(arr2.some((a) => a.includes("jane")));

it can also be done by first flattening the 2d arrays in 1 d aaray and then using includes to find whether the array contains the element or not

var arr = [['jane'],['joe'],['marry']]
var newarr=[].concat(...arr)
var v=newarr.includes('jane')
console.log(v)
发布评论

评论列表(0)

  1. 暂无评论