简体   繁体   中英

Check if an array of arrays contains a value in javascript

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 computations between.

For this input:

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM