简体   繁体   中英

Check if array exist inside an nested array JavaScript

let arr1 = [['item 1', 'item 2'],['item 3', 'item 4']]
let arr2 = ['item 1', 'item 2']

I need to check whether arr2 exist in arr1

You can use Array#some along with Array#every .

 let arr1 = [ ['item 1', 'item 2'], ['item 3', 'item 4'] ] let arr2 = ['item 1', 'item 2'] let res = arr1.some(x => x.length === arr2.length && x.every((e, i) => e === arr2[i])); console.log(res);

To keep it simple you can use the combination of every and some as below, it returns true if exists and false if not

arr1.some(i => i.length === arr2.length && i.every(it => arr2.includes(it)))

If you want a very quick and easy way to check, you could do:

arr1.findIndex(arr => { return JSON.stringify(arr) === JSON.stringify(arr2) })

Which will return the position of arr2 within arr1, or '-1' if it does not exist in arr1

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