Traversing through each element using Array method

I need to create a redux function that will add a specified number n to the fourth element of an array every time a button is clicked. However, if the element is either L or M, I do not want the addition to occur.

For example, starting with this initial array below and setting n as '5':

[M 175 0  L 326 87 L 326]

Clicking the button once should result in:

[M 175 0  L 331 87 L 326]

The fourth element is now 331

Clicking the button twice results in:

[M 175 0  L 331 92 L 326]

The fifth element becomes 92

This cycle continues until we reach the end of the array, at which point we start again from the third element.

The initial function involved mapping all the values as shown below:

var string = 'M 175 0  L 326.55444566227675 87.50000000000001  L 326.55444566227675 262.5  L 175 350  L 23.445554337723223 262.5  L 23.44555433772325 87.49999999999999 L 175 0',
    array = string.split(/\s+/),
    result = array.map(x => x === 'M' || x === 'L' ? x : +x + 5).join(' ');

console.log(result);

Refer to it in action here

Currently, I am looking for another method to achieve the same functionality for the array but am unsure of which method to use.

Answer №1

let clicks = 0;
class App extends React.Component { 
    
    state= {data:'M 175 0  L 326 87 L 326'};

    onClick() {
      clicks ++;
      this.setState({data: this.increment()}); 
    }

    /**
     * clicks  ->   Element index in array
     *    1    ----- ->4, 
     *    2    ---- -> 5.
     *    3    ---- -> 7.

     *    4    ----- ->4, 
     *    5    ---- -> 5.
     *    6    ---- -> 7.
     */
    increment() {

      const data = this.state.data.replace(/\ \ /g, " ").split(" ");
      const indexAlteredElement = (clicksModulo) => (! clicksModulo % 3) ? 7 : clicksModulo+3;               
      return data.map((e, i) => (i === indexAlteredElement(clicks%3)) ? parseInt(e)+5 : e ).join(' ')  
    
    }
     
    
    render() {
      return (
        <div>
           <div>{this.state.data} </div>
            <button onClick={this.onClick.bind(this)} style={{fontSize:20}}> Click me </button>  
        </div>
      )
  
    }


}

ReactDOM.render(<App />,  document.querySelector('.container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<section class="container"></section>

If you have any questions, feel free to ask and I will provide explanations for each line.

Answer №2

Using vanilla JS instead of react.js, you can achieve the following functionality:

function ClickHandler(s){
  this.cct = 3;    // click count
  this.str = s;    // the string
  this.num = 5;    // increase amount
  this.but = null; // the add button element
  this.res = null; // the result paragraph element
}
ClickHandler.prototype.insert = function(){
  var a = this.str.split(/\s+/);
  this.str = a[this.cct] === "L" || a[this.cct] === "M" ? a.join(" ")
                                                        : (a[this.cct] = (+a[this.cct] + this.num) + "", a.join(" "));
  this.cct = (this.cct+1)%a.length || 3;
};
ClickHandler.prototype.increase = function(){
  this.but.textContent = this.but.textContent.replace(/-?\d+/,++this.num);
};
ClickHandler.prototype.decrease = function(){
  this.but.textContent = this.but.textContent.replace(/-?\d+/,--this.num);
};

var  string = "M 175 0  L 326.55444566227675 87.50000000000001  L 326.55444566227675 262.5  L 175 350  L 23.445554337723223 262.5  L 23.44555433772325 87.49999999999999 L 175 0",
whenClicked = new ClickHandler(string),
   increase = document.getElementById("increase"),
   decrease = document.getElementById("decrease");

whenClicked.but = document.getElementById("myButton");
whenClicked.res = document.getElementById("result");
whenClicked.res.textContent = string;
whenClicked.but.addEventListener("click", function(e){
                                            this.insert();
                                            this.res.textContent = this.str;
                                          }.bind(whenClicked));
increase.addEventListener("click", whenClicked.increase.bind(whenClicked));
decrease.addEventListener("click", whenClicked.decrease.bind(whenClicked));
<button id="myButton">Add 5</button>
<p id="result"></p>
<button id="increase">Increase</button>
<button id="decrease">Decrease</button>

Answer №3

If I understand correctly, your task is to extract a single value from an existing array based on the following rule:

If the current value is M or L, do not make any changes and return the original value. Otherwise, treat it as a number, add 5 to it, and return the new value.

Here is a possible implementation:

function getValue(original, value) {

    return original === "M" || original === "L" ? original : parseFloat(original, 10) + value;

}

Whenever your handler is triggered, you can update the array, concatenate it with whitespace, and generate your SVG (assuming it represents a path).

An example code snippet:

const array = // your array
const index = 5;
function onClick () { 

     array[index] = getValue(array[index], 5);

}

If you are working with React, you may need to trigger a re-render. Your component could resemble the following structure:

class CustomComponent extends React.Component {

    constructor (props) {

        super(props);
        this.state = { array: .... } 

    } 


     render () {

        return <div>
            {/*any additional content*/}
            <button onClick={() => this.setState({

                 array: [...this.state.array.slice(4), getValue(this.state.array[4], 5), ...this.state.array.slice(5)]
             })}>Click here</button> 
        </div>;

     }

}

Answer №4

Utilize Array.prototype.reduce() for this task ( Check out more details )

The reduce() function executes a provided function for each value of the array, resulting in a single output by accumulating values from left to right.

var str = 'M 175 0  L 326.55444566227675 87.50000000000001  L 326.55444566227675 262.5  L 175 350  L 23.445554337723223 262.5  L 23.44555433772325 87.49999999999999 L 175 0';

str.split(/\s+/).reduce((prevVal, x) => x === 'M' || x === 'L' ? prevVal + ' ' + x : prevVal + ' ' + (+x + 5));

Hence, consider using reduce as an alternative method.

Answer №5

Here is a JavaScript solution that does not use React

let shapes = "M 175 0 L 326 87 L 326 262 M 175 350 L 23 262 L 23 87 M 175 0";
let shapeArray = shapes.split(" ");
let maxLength = shapeArray.length;
let index = 3;
function handleClick() {
      index++;
      if (index === maxLength) index = 3;
      if (shapeArray[index] !== 'M' && shapeArray[index] !== 'L') shapeArray[index] = parseInt(shapeArray[index]) + 5;
      console.log(shapeArray.join(' '));
};
handleClick(); handleClick(); handleClick(); handleClick(); handleClick(); handleClick();
handleClick(); handleClick(); handleClick(); handleClick(); handleClick(); handleClick();
handleClick(); handleClick(); handleClick(); handleClick(); handleClick(); handleClick();
handleClick(); handleClick(); handleClick(); handleClick(); handleClick(); handleClick();

Answer №6

Try out this code snippet:

const data = state[a].d;
const words = data.split(/\s+/);
let n = 5;
let finalWords = words.map((word, index) => {
   if (word === "L" || word === "M") {
     return word;
   } else {
    return new Number(word) + n * 4 - n * (3 - Math.min(index, 3));
   }
});

This code will generate the final array after processing elements starting from index 3 to 0.

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

How can I convert base64 data to a specific file type using React Cropper JS?

I have successfully implemented the crop functionality using react cropper js. Now, I am faced with a challenge of sending the cropped image as a file type. Currently, I can obtain the base64 string for the cropped image. However, when I submit the cropped ...

Display the content of a Vue file directly on the webpage

I am currently developing a website to showcase UI components using plain CSS. The project is built with Vue, utilizing standard HTML and CSS. One of the key features I am working on is providing users with two views for each component: 'Preview' ...

Combining PHP Variable with URL String

<td><input type="submit" onClick="window.location.href='https://www.'.$myValue.'.test.com'" value="Click!"></td> I am trying to create a button that will redirect to one of eight possible URLs based on a variable. How ...

When node.js v6.11.2 is installed on Windows 7, it does not include the correct npm version

When trying to install node.js v6.11.2 on my Windows 7 computer, I am encountering an issue where it is installing the incorrect version of npm alongside it. Even after downloading the installer directly from node.js' website which claims that 6.11.2 ...

Having trouble with adding a class on scroll?

My challenge is to extract the header from this website, by adding an additional class when the user scrolls at a position greater than 0. I thought it would be easy, but Java always presents problems for me. Here’s the code I came up with: <!DOCTY ...

Redux Thunk failing to trigger the return statement

Despite searching on Stack Overflow, I have not been able to find a solution to my current issue. My problem lies in using redux thunk to dispatch an action, as the return statement inside my thunk function does not seem to be firing. I attempted to use r ...

Is it possible for JavaScript within an <iframe> to access the parent DOM when

Is it possible for javascript in an iframe from a different domain to modify the parent's DOM? I need my iframed script to add new html elements to the parent page - any suggestions? Edit: One potential solution is using "Fragment ID Messaging" to co ...

The issue of using an import statement outside a module arises when executing Protractor

I am facing an issue while running Protractor with my two files. When I execute the command "protractor protractor.config.js", I encounter the following error: D:\work\staru-app>protractor protractor.config.js [16:57:17] I/launcher - Running ...

Experiencing a problem while attempting to start an Android React Native project

Whenever I try to execute the react-native run-android command, the following message appears: info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag. Jetifier found 998 file(s) to forward-jetify. Using 12 wo ...

What is the reason for calling Proxy on nested elements?

Trying to organize Cypress methods into a helper object using getters. The idea is to use it like this: todoApp.todoPage.todoApp.main.rows.row .first().should('have.text', 'Pay electric bill'); todoApp.todoPage.todoApp.main.rows.ro ...

Issues with login validation in HTML when utilizing JSON and PHP

While creating a login form in HTML using JSON and PHP, I encountered an issue where the if statements in the success function were not working properly. However, the beforeSend and error functions are functioning as expected. Can someone assist me in iden ...

The flow of events is not hindered by an if statement, even when the code within it is executed

I'm facing an issue where the console.log statement keeps executing even after calling the search function within the "if statements" in my code. Is there a way to prevent this from happening? function search() { /** * The Tweet checking algori ...

Stopping videos in the JQuery Cycle Plugin triggers the stop event

Currently, I have a simple cycle set up with YouTube videos using the following code: <script type="text/javascript"> $(document).ready(function () { $('#cycle').cycle({ fx: 'fade', sp ...

What is the proper way to update data in reactjs?

I previously had code that successfully updated interval data in the browser and locale without any issues. class Main extends Component { constructor(props) { super(props); this.state = {data: []} } componentWillMount() { fetch('fi ...

Enhanced coding experience with JavaScript completion and ArangoDB module management

Exploring New Horizons After more than a decade of using Eclipse for Java development, I have decided to delve into the realms of javascript and arangodb due to high demand. My current task involves developing multiple microservices to run within arangodb ...

Failure to load image logo when refreshing the page

There's something peculiar happening in my App.vue. Imagine I have a route link, let's say it's localhost/tools or any similar route. The logo image will display on this route. Take a look at the image here https://i.stack.imgur.com/6HaXI.p ...

Nuxt - Vue - Utilizing middleware on a layout in a few simple steps

Recently, I developed a middleware for authentication in my Nuxt application and now I want to utilize it within a layout. However, when trying to call the middleware using the following code: export default { middleware: 'auth', I encounte ...

What is the best way to insert information into a complicated JSON dictionary using Python?

My task involves populating a JSON API Payload before sending it in the API request. The process includes working with 2 files: A text file containing JSON payload format, named json.txt A yml file containing actual data, named tdata.yml. I am developing ...

Incorporating a static image file into a Material UI cardMedia component within a Next.js project

I am struggling to insert a static image into Material UI CardMedia component. I have tried the following code: const useStyles = makeStyles((theme) => ({ media: { height: 0, paddingTop: "56.25%", // 16:9 }, })); <CardMed ...

Express throwing module errors

I encountered an issue while attempting to expose a REST service in an electron app using expressJS. Following a tutorial, I added express and @types/express to the project. However, when trying to implement a "get" method and running the build with ng bui ...