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
)
To use a condition inside map() in React:Call the map() method on an array. Use a ternary operator to check if the condition is truthy. The operator returns the value to the left of the colon if the condition is truthy, otherwise the value to the right is returned.
Nothing wrong with putting an if statement inside the map's function. However, you have misplaced the closing parentheses and you are missing a return statement inside the function. What are trying to accomplish using map?
ES6 - Array Method map()map() method creates a new array with the results of calling a provided function on every element in this array.
ES6 provides us a new collection type called Map, which holds the key-value pairs in which values of any type can be used as either keys or values. A Map object always remembers the actual insertion order of the keys. Keys and values in a Map object may be primitive or objects. It returns the new or empty Map.
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);
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(' ')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With