I want to search in text array,and find one of this element of entry array in text , and check that if the next element or elements are numbers, return the number or those numbers
But my code works just for 1 number element after entry element , as I mentioned before, I want multiple numbers after entry element, until it reaches an element of string type.
this is my code :
const entry = [
'ENTRY', 'ZONE', 'ENTRI', 'ENTRE', 'ENTR', 'ZON', 'ZONI'
];
const text = ['HI', 'GOOD', 564, 'CLX', 'ENTRI', 'YYY', 'ENTRY', 657, 780, 34, 'XXX'];
const set = new Set(entry);
let result = [];
for (let i = 0; i < text.length; i ) {
let curr = text[i],
next = text[i 1];
if (set.has(curr) && typeof next == 'number') {
result.push(next);
}
}
console.log(result)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
so this is output :
//output : [ 657 ]
what i want :
//output : [657 , 780 , 34]
CodePudding user response:
You can add a nested loop on the same loop variable and add array values for as long they are numeric.
const entry = [
'ENTRY', 'ZONE', 'ENTRI', 'ENTRE', 'ENTR', 'ZON', 'ZONI'
];
const text = ['HI', 'GOOD', 564, 'CLX', 'ENTRI', 'YYY', 'ENTRY', 657, 780, 34, 'XXX'];
const set = new Set(entry);
let result = [];
for (let i = 0; i < text.length; i ) {
if (set.has(text[i])) {
while (typeof text[i 1] == "number") {
result.push(text[ i]);
}
}
}
console.log(result)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
your condition says that the valid element has to come right after the set member, which only applied to the first element not every element.
a different way to do it is to turn on a flag that a member was found and turn it off once you reach another string that's not a member.
const entry = ['ENTRY' , 'ZONE' , 'ENTRI' , 'ENTRE' , 'ENTR' ,'ZON' , 'ZONI'];
const text = ['hi' , 'good' , 564 , 'clx' , 'entri' , 'yyyy' , 'ENTRY' ,657 , 780 , 34 , 'xxxx'];
const set = new Set(entry);
let result = [];
let isAfterMatch = false
for (let i = 0; i < text.length; i ) {
const curr = text[i];
if (isAfterMatch && typeof curr === 'number') {
result.push(curr);
} else {
isAfterMatch = set.has(curr)
}
}
console.log(result)
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>