How can I achieve this kind of conditions in javascript? (via: vanilla or lodash)
const array1 = [1, 2]
const array2 = [1, 2, 3, 4] //true
const array2 = [1, 3, 2, 4] //true
const array2 = [4, 3, 2, 1] //false
const array2 = [2, 3, 1, 4] //false
I tried something like this.
const _ = require('lodash');
const array1 = [1, 2];
const array2 = [1, 2, 3, 4];
const trimmed = array2.filter((n) => combinations.indexOf(n) > -1);
const isEqual = _.isEqualWith(array1, trimmed);
console.log(isEqual);
Please post if you have much cleaner and much flexible code for this problem.
2
Answers
Use
Array.every()
to check if each item inarr2
is either not included inarr1
or is found in placei
(the current index ofarr1
):A variation on this would be to shallow clone the 1st array using destructuring a rest syntax, and then use
Array.shift()
to always check the current 1st item ofarr1
:With lodash – get the intersection of
arr2
andarr1
(same items, regardless of order), and then check if it’s equal toarr1
(same items, same order):Considering all elements in array1 will be present in array2, you apply two pointer approach.
Something like this: