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
asked May 24, 2021 at 17:07
geek glance
1112 silver badges12 bronze badges
-
You will have to use some and every. Does the order matter?epascarello– epascarello2021年05月24日 17:11:18 +00:00Commented May 24, 2021 at 17:11
-
This is a very popular gist that tackle this: jsfiddle.net/SamyBencherif/8352y6ywRodrigo Rodrigues– Rodrigo Rodrigues2021年05月24日 17:26:32 +00:00Commented May 24, 2021 at 17:26
3 Answers 3
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);
answered May 24, 2021 at 17:15
Unmitigated
91.5k12 gold badges103 silver badges109 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
geek glance
Thanks for the answer, now If I want to delete that item how can I?
Unmitigated
You can use
arr1.splice(arr1.findIndex(x => x.length === arr2.length && x.every((e, i) => e === arr2[i])), 1)Unmitigated
@geekglance No problem.
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)))
answered May 24, 2021 at 17:12
Murali krishna Gundoji
111 bronze badge
2 Comments
geek glance
If I want to delete that item how can i?
Murali krishna Gundoji
1 . You can use findIndex and splice
let res = arr1.findIndex(x => x.length === arr2.length && x.every((e, i) => e === arr2[i])); arr1.splice(0,1); 2. you can directly use filter arr1 = arr1.filter(x => x.length !== arr2.length || x.some((e, i) => e !== arr2[i]));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
answered May 24, 2021 at 17:12
joshua miller
1,7661 gold badge15 silver badges24 bronze badges
1 Comment
joshua miller
Quick note: This will only work if you are trying to match the order (which you might be seeing as in JS arrays are ordered)
lang-js