I’m trying to check whether a sub-array exists in an array so that I could discard or avoid adding.
For example
Let’s assume I have an array like this
[
[-5, 0, 5], [-5, 2, 3],
[-3, 0, 3,], [-3, 1, 2],
[-1, -1, 2], [-1, 0, 1]
]
and got another pair as
[-3, 1, 2]
to add but it’s already available in existing data so need to check and avoid adding.
What I have tried so far
let mapped = result.map(item => item.join());
let match = `${item1},${item2},${item3}`; // coming items => item1, item2, item3
if(mapped.includes(match)){
...
} else {
...
}
Is this okay to use or any better way to check it when we have a huge amount of data?
3
Answers
Using array methods
.find()
and.every()
:I would just iterate over your array and check if an element is equal to the element you want to add. Assuming you are only dealing with numbers, you can check that by converting your array to a string.
If that is the only data you have to work with, a simple comparison might be best.
The some() and every() functions will early exit:.