Combination of icons in JavaScript

Given a text array and an array of symbols, the current code performs the following:

It looks for symbols in the text array and if the next element is also a symbol, it combines both symbols (the current one and the next one) with a '/' between them into a new array. This creates pairs of symbols.

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'],

However, there are cases where there are 3 consecutive elements in the text array - 'XLM', 'DASH', 'COIN'. The output includes two pairs based on these consecutive symbols: 'XLM/DASH' and 'DASH/COIN'.

I would like to modify this behavior so that if there are no additional symbols after the third symbol, only the first and second symbols are returned as pairs.

Desired output from the text array: ['BCH/LTC','XLM/DASH']

If there is a fourth symbol present, then I want to return the third and fourth symbols in pairs as well.

Answer №1

One alternative method involves leveraging the concepts utilized in your previous work with the reduce function. The concept revolves around introducing a variable to keep track of whether the second pair matches the first pair of the subsequent match if one exists.

const data = ['XLM', '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'];


let lastSecondIndex = -1; 
const symbolSet = new Set(symbols);
const output = data.reduce((accumulator, current, index, source) => {
    const nextItem = source[index + 1];
    if (symbolSet.has(current) && symbolSet.has(nextItem)){  
        if(lastSecondIndex !== index){
          accumulator.push(`${current}/${nextItem}`); 
          lastSecondIndex = index+1; 
        }
    }
    return accumulator;
}, []);

console.log(output)

Answer №2

Consider utilizing a for loop for this task

const texts = [
  'word1', 'word2',
  'number1', 'number2',
  'currency1', 'amount1',
  'phrase1', 'phrase2A',
  'data1', 'value1',
  'item1', 'quantity1',
  'crypto1', 'crypto2',
  'pair1', 'pair2',
  'asset1'
];


const symbols = ['crypto1', 'crypto2', 'currency1', 'phrase2A', 'asset1'];

//Extract all matching pairs from the text
const symbolSet = new Set(symbols);

let output = []
for (let i = 0; i < texts.length; i += 2) {
  let currentData = texts[i], nextData = texts[i + 1];
  if (symbolSet.has(currentData) && symbolSet.has(nextData)) {
    output.push(`${currentData}/${nextData}`)
  }
}

console.log(output)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring Next.js: Leveraging fetch to retrieve data in getServerSideProps and passing it to the client via query parameters

I'm utilizing a getServerSideProps function on the directory page. pages/catalog/index.js export async function getServerSideProps(ctx) { const response = await fetch( `http://someDomen.com/api/ipro/catalog?${ctx?.query?.page ? `page=${ctx.quer ...

Is there a way to determine the dimensions of an HTML element? (taking into account added elements)

It seems that the current situation is not feasible at this time. I am working on an animation that requires an element to move from an absolute position to an inline one. The challenge is that I cannot predict how the container or the element itself will ...

One div takes a backseat to the other div

I recently delved into learning Bootstrap, but I'm baffled as to why one div is appearing behind another. <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Fa ...

What are some strategies for troubleshooting asynchronous errors in JavaScript function calls?

I'm currently working on an asynchronous JavaScript code that utilizes the async method findDevices from the class Devices, which is located in a separate file. This method involves performing a mongo find operation within the IDevices collection. Her ...

Interacting with dynamically loaded HTML content within a div is restricted

On my main HTML page, I have implemented a functionality that allows loading other HTML pages into a specific div using jQuery. The code snippet looks like this: $('.controlPanelTab').click(function() { $(this).addClass('active').s ...

The function data() is coming back as null

This is the code snippet I am working with: $.getJSON("link here", function (result) { $.each(result, function (i, value) { $('.usersOfGroupList').append($("<li id='userElement' data-userId='' ></li>") ...

Erase the dynamically loaded page using ajax and conceal the div

Currently, I am utilizing the .on() method with jQuery to display a specific div, and also using .load() to fetch a particular div from a web page hosted on my server. My query is how can I close this div when clicking outside of it, along with removing i ...

Incorrect Tooltip DisplayWhat could be causing the issue with

I am facing an issue when trying to add a tooltip to a glyphicon within a tile. It doesn't seem to work correctly when it should. However, placing the tooltip outside of the tile works fine. I'm quite perplexed and would greatly appreciate any as ...

Generating various API calls and delivering them to a template (Express + Node.js + Facebook open graph)

I am currently developing a unique Express Node.js application that utilizes the extraordinary capabilities of this remarkable Facebook SDK. Allow me to present my existing route for the root: app.get('/', Facebook.loginRequired(), function (req ...

Trigger next animation after the completion of current animation using Jquery animate callback

Is there a simpler way to achieve this task? var index = 0; while (index < 5) { $(this).find(".ui-stars-star-on-large:eq(" + index + ")").animate({ width: w + 'px' }, 200, "swing"); index++; } ...

What could be the reason for the absence of a TypeScript error in this situation?

Why is it that the code below (inside an arbitrary Class) does not show a TypeScript error in VSCode as expected? protected someMethod (someArg?: boolean) { this.doSomething(someArg) } protected doSomething (mustBePassedBoolean: boolean) { /* ... * ...

Tips for personalizing the css styles of an alert box?

I am in need of customizing the alert box using CSS attributes. Currently, I am able to achieve a similar effect with the code below: JQUERY: $('<div class="alertMessage">Error first</div>') .insertAfter($('#componentName' ...

Issue with post-processing filters in Three.JS r71: Transparent renderer is not functioning as expected

I am attempting to implement a BloomPass on my current scene and want the background of the containing page to show through. However, when I apply the BloomPass, the background turns black. You can see my example here:http://plnkr.co/edit/0mp0jaGVF6it52HY ...

Surprising "unexpected end of line" JavaScript lint notification out of nowhere

In this simplified version of my JavaScript code: function addContent() { var content = []; content.append( makeVal({ value : 1 }) ); // lint message generated } After running a lint program, I received the followi ...

Where is the destination of the response in a Client-Side API Call?

I have developed an API that accepts a person's name and provides information about them in return. To simplify the usage of my API for third parties on their websites, I have decided to create a JavaScript widget that can be embedded using a script ...

Looking for visible elements in WebDriverIO?

Currently, I am developing a test suite using WebDriverIO for a website with multiple duplicate elements that are selectively displayed based on user interaction... For example, the site may contain five buttons that each open a tooltip. These tooltips ar ...

accessing HTML form via XMLHttpRequest (XHR)

One challenge I'm facing is retrieving form content using XmlHttpRequest, but it doesn't seem to post anything on the subsequent page. If I include the form within the same page where my script is used, it does post data. However, the informatio ...

Ensure all <li> tags within a HTML document exhibit consistent jquery mousedown and hover effects, abstaining from the assignment of unique IDs to each

I understand that this approach might not be correct, but I wanted to create a simulation of what I am trying to achieve. Is there a way for each <li> element within a specific <ul class="myul"> to have separate mousedown, mouseout, hover effe ...

Operating on Javascript Objects with Randomized Keys

Once I retrieve my data from firebase, the result is an object containing multiple child objects. myObj = { "J251525" : { "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6c3823212 ...

AngularJS Banner: Displaying Current Calendar Week and Increasing by 10 Days

I'm brand new to Angular and currently encountering some issues. Here's what I'm trying to create: I need to display the current Date: yyyy-MM-ss (Functional) I want to show the current Calendar Week: yyyy-Www (Not Working) When a butto ...