I have an array of words, and I want to search the words in text array , find them and check if next element or elements after word are numbers , push the number or numbers with word in new object and push object to new array. like this:
words = ['blue' , 'red' , 'yellow' , 'grin' , 'black' , 'white'];
text = ['xxx' , 'yyy' , 'red' , 'zzz' , 'black' , 65 , 54 , 'white' , 'aaa' , 'yellow' , 50 , 'ppp'];
Output I want:
[{'black' : [65 , 54] , 'yellow' : [50]}];
But my current code just returns the numbers after word and push them in new array:
words = ['blue' , 'red' , 'yellow' , 'grin' , 'black' , 'white'];
text = ['xxx' , 'yyy' , 'red' , 'zzz' , 'black' , 65 , 54 , 'white' , 'aaa' , 'yellow' , 50, 'ppp'];
const set = new Set(words);
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)
//output : [65 , 54 , 50]
So how can I push numbers with their keys to an array?