1

Suppose a string like this 1.2-1.4. What I want is to split this string at -, then multiply each of the parts by a factor, and finally return a string like part1*factor-part2*factor.

Ie. if the string is declared like this: var range = '1.2-1.4';, and factor is declared like this: var factor = 10;, I would like get a string like 12-14.

So I did the following so far:

    var range = '1.2-1.4';
    var factor = '10';
    let complex = '';

    const parts = range.split("-");

    parts.forEach(function(element){
        // what is the shortest code that would concat the parts in the way I want?
    });

TIA.

Faye D.
  • 833
  • 1
  • 3
  • 16

2 Answers2

2

Using the map() function together with split() and join() is probably the most straightforward.

const range = '1.2-1.4';
const factor = '10';
const result = range.split('-').map(v => +v * +factor).join('-');

console.log(result); // 12-14
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
  • 2
    Note: The [unary plus operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus) converts its operand into a number. You may prefer [`Number()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/Number) for more verbose code. Refer to this [comparison of conversion methods](https://stackoverflow.com/a/17106702/13561410) for more ways. – Oskar Grosser Mar 13 '23 at 09:10
-1

You can use the map() method to create a new array with the multiplied values and then use join() to concatenate them with the factor and the - separator.

var range = '1.2-1.4';
var factor = 10;
let complex = '';

const parts = range.split("-");

const multipliedParts = parts.map(part => parseFloat(part) * factor);

complex = multipliedParts.join(`-${factor}`);

console.log(complex);

This should output 12-14 for the given range and factor.