The current code returns all found elements if the array contains one element comp = ['bbb'] see example.
How can I change the code to output the array as a strict match, i.e. log [[ 'a', 'bbb', 'c' ]] ?
For other cases, no changes are required.
I've attached the actual code and wrote the output examples.
function datasearch() {
let array = [['a', 'bbb', 'c'], ['r', 'bbbfff', 'y',],['w', 'bbbfffkkk', 'u',]]
let comp = ['bbb'];
let ans = [];
for (let i = 0; i < array.length; i++) {
for (el of array[i]) {
if (comp.every(y => el.includes(y))) {
ans.push(array[i]);
break;
}
}
}
console.log(ans);
}
now
comp = ['bbb']
log [ [ 'a', 'bbb', 'c' ],[ 'r', 'bbbfff', 'y' ],[ 'w', 'bbbfffkkk', 'u' ] ]
Expected result for search with one array element
comp = ['bbb']
log [[ 'a', 'bbb', 'c' ]]
For other cases, everything is as in the current code For example:
comp = ['bbb','fff']
log [ [ 'r', 'bbbfff', 'y' ], [ 'w', 'bbbfffkkk', 'u' ] ]
It seems like you need two separate behaviors, which need to be treated independently.
comp has only one element, you need to check for an exact match in the source array array.comp contains multiple elements, you only check if the elements are present in the source array (current implementation).Code will become:
function datasearch() {
let array = [['a', 'bbb', 'c'], ['r', 'bbbfff', 'y',], ['w', 'bbbfffkkk', 'u',]]
let comp = ['bbb'];
let ans = [];
for (let i = 0; i < array.length; i++) {
if (comp.length == 1) {
for (el of array[i]) {
if (el === comp[0]) {
ans.push(array[i]);
break;
}
}
} else {
for (el of array[i]) {
if (comp.every(y => el.includes(y))) {
ans.push(array[i]);
break;
}
}
}
}
console.log(ans);
}
If I understood you correctly, then perhaps such a solution can help you:
function datasearch(comp = [], strictCompare = false) {
const array = [
['a', 'bbb', 'c'],
['r', 'bbbfff', 'y', ],
['w', 'bbbfffkkk', 'u', ]
]
const ans = [];
for (let i = 0; i < array.length; i++) {
for (el of array[i]) {
if (comp.every(y => (strictCompare) ? el === y : el.includes(y))) {
ans.push(array[i]);
break;
}
}
}
return ans;
}
console.log('not strict', datasearch(['bbb']));
console.log('strict', datasearch(['bbb'], true));
console.log('combine(strict & not strict)', datasearch(['bbb'], true).concat(datasearch(['kkk'])));