I have a text and a symbols array , so current code does this :
Find a symbol from the text array and if next element is also a symbol, push both (the current symbol and the next element, which is also a symbol)with one / between them to a new array.(Make a symbol pair)
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','COIN','ETH','LTC','BNB','BCH','XRP'];
//Return all the pair in text
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;
}, []);
//output :
//['BCH/LTC','XLM/DASH','DASH/COIN'],
But Here , there are 3 consecutive elements in text array , 'XLM', 'DASH' ,'COIN'
, and as you see in the output ,it returns two pair of 3 consecutive symbols :'XLM/DASH','DASH/COIN'
I want to ignore it and if there is no other symbol after the third symbol, just return the first and second symbols in pairs
what i want from the text array :
['BCH/LTC','XLM/DASH']
And if there is a fourth symbol, return the third and fourth symbols in pairs
CodePudding user response:
Try using for
loop
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', 'COIN', 'ETH', 'LTC', 'BNB', 'BCH', 'XRP'];
//Return all the pair in text
const set = new Set(symbols);
let result = []
for (let i = 0; i < text.length; i = 2) {
let curr = text[i], next = text[i 1];
if (set.has(curr) && set.has(next)) {
result.push(`${curr}/${next}`)
}
}
console.log(result)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Another approach is one adapted from the work you have done with reduce
. The idea is to add a variable, which will track whether the last second pair matches the first pair of the immediate next match if it exists.
const text = ['aaaa', 'BTC','08', '324','ETH', '233','yyyy', '30000','XRP', 'xxxxxGG','llll', '546','BCH', 'LTC','xxxyyy', '435','XLM', 'DASH','COIN', 'ETH'];
const symbols = ['XLM', 'XTZ', 'BTC', 'DASH', 'COIN', 'ETH', 'LTC', 'BNB', 'BCH', 'XRP'];
// initialize this
let lastSecondPairI = 0;
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)){
// check if it does not match the current element (by i)
if(lastSecondPairI !== i){
acc.push(`${curr}/${next}`);
// update the value every time there's not a match
lastSecondPairI = i 1;
}
}
return acc;
}, []);
console.log(result)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>