Koala7
Koala7

Reputation: 1404

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

Upvotes: 8

Views: 588

Answers (6)

C L K Kissane
C L K Kissane

Reputation: 34

Use this:

let string = state[a].d
let array = string.split(/\s+/)
var n=5;
var finalArray=array.map(function(current, index) {
   if (current=="L" || current=="M") {
     return current;
   }else{
    return new Number(current)+n*4-n*(3-Math.min(index,3));
   }

});

It gives you the final array that you would get after running it through the process completely from index 3 (element 4) to 0.

Upvotes: 0

Sagar Shetty
Sagar Shetty

Reputation: 157

You can use Array.prototype.reduce() ( Refer )

The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

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

So reduce is your other method that you can use.

Upvotes: 1

adz5A
adz5A

Reputation: 2032

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

     }

}

Upvotes: 1

Redu
Redu

Reputation: 26181

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>

Upvotes: 1

kevin ternet
kevin ternet

Reputation: 4612

I propose you a solution in pure JS without react

var string = "M 175 0 L 326 87 L 326 262 M 175 350 L 23 262 L 23 87 M 175 0";
var array = string.split(" ");
var max = array.length;
var i = 3;
var clic = () => {
      i++;
      if (i === max) i = 3;
      if (array[i] !== 'M' && array[i] !== 'L') array[i] = parseInt(array[i]) + 5;
      console.log(array.join(' '));
};
clic(); clic(); clic(); clic(); clic(); clic();
clic(); clic(); clic(); clic(); clic(); clic();
clic(); clic(); clic(); clic(); clic(); clic();
clic(); clic(); clic(); clic(); clic(); clic();

Upvotes: 0

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93323

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

Upvotes: 1

Related Questions