I have a text array and a symbols and current code do this : search in the text array and if there is an element of the symbols array in the text array, push it in a new array (coinsArr)
I want to find a symbol from the text array and if next element is also a symbol, push both of them(the current symbol and the element and the next element, which is also a symbol)with one / between them.
So this is my code:
const text = [
'aaaa', 'BTC',
'08', '324',
'ETH', '233',
'yyyy', '30000',
'XRP', 'xxxxxGG',
'llll', '546',
'BCH', 'LTC',
'xxxyyy', '435',
'XLM', 'DASH',
'COIN'
];
const symbols = ['XLM', 'XTZ', 'BTC', 'DASH', 'ETH', 'LTC', 'BNB', 'BCH', 'XRP'];
const coinsArr = [];
for (let i = 0; i < text.length; i ) {
for (let j = 0; j < symbols.length; j ) {
const el = symbols[j];
if (el == text[i]) {
coinsArr.push(el);
}
}
}
console.log({
'coinsArr': coinsArr
});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
And gives this output(just search in text array and find symbols) :
['BTC','ETH','XRP','BCH','LTC','XLM','DASH','COIN']
But I want this output :
['BCH/LTC','XLM/DASH']
CodePudding user response:
You can easily achieve the result using reduce and optimise the access of symbols
using Set
const text = [
'aaaa', 'BTC',
'08', '324',
'ETH', '233',
'yyyy', '30000',
'XRP', 'xxxxxGG',
'llll', '546',
'BCH', 'LTC',
'xxxyyy', '435',
'XLM', 'DASH',
'COIN'
];
const symbols = ['XLM', 'XTZ', 'BTC', 'DASH', 'ETH', 'LTC', 'BNB', 'BCH', 'XRP'];
const set = new Set(symbols);
const result = text.reduce((acc, curr, i, src) => {
const next = src[i 1];
if (set.has(curr) && set.has(next)) acc.push(`${curr}/${next}`);
return acc;
}, []);
console.log(result);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>