Reputation:
I need to check if a string has any indexOf of a few values. I would like to avoid things like this:
let filter = tasks.filter(
x =>
x.eventData.workflow_name === brand &&
(x.eventData.task_queue_name.indexOf('Value1') == -1 &&
x.eventData.task_queue_name.indexOf('_Value2') == -1 &&
x.eventData.task_queue_name.indexOf('Value3') == -1 &&
x.eventData.task_queue_name.indexOf('BANG_Value4') == -1)
)
I was trying to create an array like const VALUES_TO_SKIP = ['Value1', ...]
and write indexOf condition in a single line.
Is possible to avoid a bunch of value.indexOf(...)
?
Upvotes: 1
Views: 54
Reputation: 1074959
I was trying to create an array like
const VALUES_TO_SKIP = ['Value1', ...]
and writeindexOf
condition in a single line.
I'd use a regular expression with an alternation and test
instead:
let filter = tasks.filter(x =>
x.eventData.workflow_name === brand && !/Value1|_Value2|Value3|BANG_Value4/.test(x.eventData.task_queue_name)
);
Live Example:
const tasks = [
{
eventData: {
workflow_name: 'foo',
task_queue_name: 'xxx BANG_Value4 yyy',
}
},
{
eventData: {
workflow_name: 'foo',
task_queue_name: 'none of them',
}
},
{
eventData: {
workflow_name: 'bar',
task_queue_name: 'Dogs loves BANG_Value4',
}
},
{
eventData: {
workflow_name: 'foo',
task_queue_name: 'none of them again',
}
},
{
eventData: {
workflow_name: 'foo',
task_queue_name: '_Value2 yyy',
}
}
];
const brand = "foo";
let filter = tasks.filter(x =>
x.eventData.workflow_name === brand && !/Value1|_Value2|Value3|BANG_Value4/.test(x.eventData.task_queue_name)
);
console.log(filter);
.as-console-wrapper {
max-height: 100% !important;
}
Upvotes: 1
Reputation: 23535
You can use an Array.some
or Array.every
like :
// The values to Test out
const arrayOfValue = [
'Value1',
'_Value2',
'Value3',
'BANG_Value4',
];
// Your data to filters
const tasks = [{
eventData: {
workflow_name: 'brand',
task_queue_name: 'BANG_Value3 and Value2 and Value3',
},
}, {
eventData: {
workflow_name: 'brand',
task_queue_name: 'Dogs loves cat',
},
}, {
eventData: {
workflow_name: 'brand',
task_queue_name: 'Dogs loves BANG_Value4',
},
}];
const brand = 'brand';
const filtered = tasks.filter(x =>
x.eventData.workflow_name === brand &&
!arrayOfValue.some(y => x.eventData.task_queue_name.includes(y))
);
console.log(filtered);
Upvotes: 2
Reputation: 138417
You could just use every
to check multiple keys and includes
in favor of indexOf:
['Value1', '_Value2', 'Value3'].every(key =>
!x.eventData.task_queue_name.includes(key))
Upvotes: 1