I have list like ['one', 'two', 'finish', 'one', 'two', 'two']
:
If 'two' comes before 'finish' and then after finish I need to return checkFlag = true
I tried with below code.
const empList = ['one', 'two', 'finish', 'one', 'two', 'two'];
const map = new Map(empList.map((emp, index) => [emp, index]));
const checkFlag = map.get('two') < map.get('finish');
console.log(checkFlag);
CodePudding user response:
const empList = ['one', 'two', 'finish', 'one', 'two', 'two'];
const firstPoint = empList.indexOf('two');
const finishIndex = empList.indexOf('finish');
const lastPoint = empList.lastIndexOf('two');
console.log(firstPoint < finishIndex && finishIndex < lastPoint)
CodePudding user response:
const empList = ['one', 'two', 'finish', 'one', 'two', 'two'];
const finish = empList.indexOf('finish');
const checkFlag = empList.indexOf('two') < finish && empList.lastIndexOf('two') > finish;
console.log(checkFlag);
CodePudding user response:
There is also a way to do this in just one iteration of that array, which would be something like this:
const empList = ['one', 'two', 'finish', 'one', 'two', 'two'];
var checkFlag = false
const relevant = []
for (const element of empList){
if(element === "two"){
relevant.push(true)
} else if(element === "finish"){
relevant.push(false)
}
}
if(
relevant[0]
&& relevant[relevant.length - 1]
&& relevant.length >= 3
){
checkFlag = true
}
console.log(checkFlag)