Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Statement in a map function with es6

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 )

like image 794
Koala7 Avatar asked Jan 09 '17 18:01

Koala7


People also ask

How do I add an IF condition to a map?

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.

Can you put an if statement in a map function?

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?

How do I use the map function in ES6?

ES6 - Array Method map()map() method creates a new array with the results of calling a provided function on every element in this array.

Is ES6 a map feature?

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.


Video Answer


2 Answers

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);
like image 199
Phil Poore Avatar answered Sep 23 '22 19:09

Phil Poore


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(' ')
like image 32
2 revs Avatar answered Sep 19 '22 19:09

2 revs