I have array with some element that I want to check if some element combination exist in array that target element is following by any element of checkingSet, if yes, then return true otherwise, return false. For example, if inputArray is ['a', 'b', 'c', 'd'] and looking for combination is ['a', 'd'] then it should return true because inputArray has both in the right sequence. if inputArray is ['d', 'b', 'c', 'd', 'a'] and the combination is ['a', 'd'], then it should be false because inputArray includes both elements but in wrong order or
isExist(['a', 'd']) => true
isExist(['a', 'a', 'd']) => true
isExist(['e', 'd']) => false
I can use Set and while loop but I am wondering if any more elegant or modern way to do?
export function isExist(checkArray): boolean {
let hasA = false;
let hasB = false;
checkingSet = new Set(['b', 'c', 'd'])
const target = 'a'
inputArray = [...checkArray]
while (inputArray && !!inputArray.length) {
const lastOne = inputArray.pop();
if (!hasA && !!lastOne) {
hasA = chekcingSet.has(lastOne);
}
if (!hasB && !!lastOne) {
hasB = lastOne === target;
}
if (hasA && hasB) {
return true;
}
}
return false;
}
To check that the array contains 'a'
, and after this 'a'
at least one of ['b', 'c', 'd']
is in the array you can do this. First, get the index of the first 'a'
in the array, then check if some value of ['b', 'c', 'd']
is included in that array after this start index.
function doesExist(arr) {
const startPos = arr.indexOf('a')
if (startPos < 0)
return false
return ['b', 'c', 'd'].some(char => arr.includes(char, startPos + 1))
}
console.log(doesExist(['a', 'd']))
console.log(doesExist(['a', 'a', 'd']))
console.log(doesExist(['e', 'd']))
console.log(doesExist(['d', 'a']))