- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-07-2023 12:08 AM
Hi let I have a list L=['abcc','cabc','xydk','xyii']
I want to write a script such that
1. if L contains elements which have substring 'ab' only then return 0;
2. if L contains elements which have substring 'xy' only then return 1;
3. If both then return 2.
Please help in js.
Solved! Go to Solution.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-07-2023 12:18 AM - edited 12-07-2023 12:20 AM
Hi @Rosy14 ,
Can u try below code
function checkSubstrings(arr) {
let hasAB = false;
let hasXY = false;
for (let i = 0; i < arr.length; i++) {
if (arr[i].includes('ab')) {
hasAB = true;
} else if (arr[i].includes('xy')) {
hasXY = true;
}
}
if (hasAB && hasXY) {
return 2;
} else if (hasAB) {
return 0;
} else if (hasXY) {
return 1;
} else {
return -1; // Indicates no match
}
}
// Example usage with your list
let myList = ['abcc', 'cabc', 'xydk', 'xyii'];
let result = checkSubstrings(myList);
console.log(result);
Thanks,
Danish
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-07-2023 12:18 AM - edited 12-07-2023 12:20 AM
Hi @Rosy14 ,
Can u try below code
function checkSubstrings(arr) {
let hasAB = false;
let hasXY = false;
for (let i = 0; i < arr.length; i++) {
if (arr[i].includes('ab')) {
hasAB = true;
} else if (arr[i].includes('xy')) {
hasXY = true;
}
}
if (hasAB && hasXY) {
return 2;
} else if (hasAB) {
return 0;
} else if (hasXY) {
return 1;
} else {
return -1; // Indicates no match
}
}
// Example usage with your list
let myList = ['abcc', 'cabc', 'xydk', 'xyii'];
let result = checkSubstrings(myList);
console.log(result);
Thanks,
Danish
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-07-2023 12:33 AM - edited 12-07-2023 12:35 AM
Hi @Rosy14 ,
I have tried in my pdi its working fine
3. If both then return 2.
1. if L contains elements which have substring 'ab' only then return 0;
2. if L contains elements which have substring 'xy' only then return 1;
Use below script
var myList = ['cc', 'cc', 'xydk', 'xyii'];
var hasAB = false;
var hasXY = false;
for (var i = 0; i < myList.length; i++) {
var element = myList[i];
if (element === 'ab' || element.startsWith('ab') || element.endsWith('ab')) {
hasAB = true;
}
if (element === 'xy' || element.startsWith('xy') || element.endsWith('xy')) {
hasXY = true;
} }
if (hasAB && !hasXY) {
gs.info('Result: 0');
//return 0
} else if (!hasAB && hasXY) {
gs.info('Result: 1');
//return 1;
} else if (hasAB && hasXY) {
gs.info('Result: 2');
//return 2
} else {
gs.info('Result: No match');
}
Mark it helpful and solution proposed.
Thanks,
Anand
