9

I nee to use the conditional statement in a map function

I am duplicating each single value of a path d in a SVG but i do not want this happening for the objects M and L of the array

Here is an example of the array as 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

This is an example to my case without the conditional statement

let neWd = array.map(x => { return x * 2; }).reverse().join(' ')

how can i write down this in e6 ? I don not want the multiplication happening for the elements L and M ( something like if x ? 'M' : 'L' return )

Phil Poore
  • 2,086
  • 19
  • 30
Koala7
  • 1,340
  • 7
  • 41
  • 83

3 Answers3

17

I'm not sure why your using the reverse function also, reversing the svg path is slightly more complicated.

This code snippet doubles all the numbers, but leaves M and L intact.

In effect scaling up the svg path by 200%

var array = "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".split(" ");

let neWd = array.map(x => {
 if (x === 'M' || x === 'L'){
  return x;
 }else{
  return x * 2;
 }
}).join(' ')

console.log(neWd);
Phil Poore
  • 2,086
  • 19
  • 30
  • yes it was not necessary add the reverse.join for the question, this was because i need those values applied in the dom so in order to map i converted in an array and then in a string again – Koala7 Jan 09 '17 at 19:18
  • 1
    `join` makes sense like you say to get from array back to a string. just wanted to stress `reverse` on the svg path will not reverse the path. – Phil Poore Jan 09 '17 at 19:20
6

Yes, just do it:

let neWd = array.map(x => {
    if (x == "M" || x == "L")
        return x; // unchanged
    else
        return String(parseInt(x, 10) * 2);
}).reverse().join(' ')
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • You still haven't shown your case (an example of `array`) so I cannot specialise the answer more. But you can [edit] it yourself if you want – Bergi Jan 09 '17 at 18:55
  • this is the array converted in a 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 – Koala7 Jan 09 '17 at 19:00
  • 1
    That's a string, not an array. Have you parsed it into some data structure such as `[{op:"M", vals:[175,0]}, {op:"L", vals:[326.55444566227675, 87.5]}, …]`? – Bergi Jan 09 '17 at 21:51
1

Using Es6 syntax

let neWd = array.map((x) => (x == "M" || x == "L") ?
x : String(parseInt(x, 10) * 2)).reverse().join(' ')
Syed Ali Shahzil
  • 1,079
  • 1
  • 11
  • 17