Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

108
Views
Array Method for looping to each element

I am writing a redux function where anytime i click a button i have to add a number n to the fourth element of the array. If the element is L or M i do not want the addition

Example I have this array below, and the number to add, i.e. n is '5'

[M 175 0  L 326 87 L 326]

I click the button once and the array becomes

[M 175 0  L 331 87 L 326]

The fourth element becomes 331

I click the button twice and the array becomes

[M 175 0  L 331 92 L 326]

The fifth element becomes 92

And so on until the array finishes and i start again from the third element

This is my initial function where i was mapping all the values

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);

See here in action

but now i need an other array method to achieve that but i do not know which and how

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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>

Let me know if you have any question .. just give the line , and i will explain

over 4 years ago · Santiago Trujillo Report

0

While not by react.js but pure JS you might do as follows;

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>

over 4 years ago · Santiago Trujillo Report

0

Your problem is, if I understand correctly, from an existing array, obtain a one (not necessarily new) while following the rule :

If the current value is M or L do nothing, return the value, else   
consider it a number, add 5 to it and return.

Consider the implemation :

function getValue (original, value) {

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

}

So everytime your handler is triggered you can update your array, join it with whitespace and render your SVG (i suppose this is a path).

Something along those lines :

const array = // your array
const index = 5;
function onClick () { // you need to attach this handler to whatever node / object you are listening to

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

}

If you are using React, you may want to trigger a rerender. Your component will look like something like this :

class C extends React.Component {

    constructor (props) {

        super(props);
        this.state = { array: .... } // the state is initialized with your array


    } 


     render () {

        return <div>
            {/*anything you want*/}
            <button onClick={() => this.setState({

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

     }

}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!