Skip to content Skip to sidebar Skip to footer

Sum Of A Number For Each Element In An Array

I am working in a redux function where i want for each element in array the sum with n number This is the code let neWd = array.map(x => { if (x === 'M' || x === 'L'){ ret

Solution 1:

Assuming you have a string and it is splitted with ' ' and then you get each element as string. You need to cast it to a number, in this example with an unary + for incrementing with 5.

This proposal splits on white space, which can be more than one characters long.

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

Post a Comment for "Sum Of A Number For Each Element In An Array"