For example,
const target = [1,2,3,4,5,"abc", "def", [10,1000]]
test(target, [2,3,4]) === true
test(target, [4,5,"abc"]) === true
test(target, ["def", [10, 1000]) === true
test(target, [0,1,2]) === false
test(target, ["abc",5,4]) === false
test(target, [2,4]) === false
test(target, ["def", [1000, 10]]) === false
Currently I'm using JSON.stringify
to accomplish this (and with replacer
function if the elements contain things like BigInt
values):
`,${JSON.stringify(target).slice(1, -1)},`.includes(`,${JSON.stringify(arr).slice(1, -1)},`)
to check if target
contains arr
with the same consecutive ordering of elements, however this seems a bit too hacky so I wonder if there are better ways to accomplish it?
EDIT:
I'm not sure why this question is marked as a duplicate of Check if an array includes an array in javascript since it's a completely different question?
EDIT 2:
I have edited the title to be more precise, to match what I really meant and what the examples here have shown. And I still don't think it's a duplicate of
Javascript array contains/includes sub array
since "sub array" doesn't sound like the same thing and it says The order of the subarray is important but the actual offset it not important
which again not sure if it's about the same question.
Also I'm aware that this can be done by brute force loop/recursion kind of solutions instead of the JSON.stringify
"hack" I use, I'm more interested in whether there are more performant, or safer, or more idiomatic ways to do it than this "hackish" solution (And I know JSON.stringify
cannot serialize things like BigInt
, which needs a replacer
function to make it work)
EDIT 3:
Add more examples to illustrate what I try to accomplish better.