jmk jmk - 6 months ago 21
Javascript Question

converting array to different types (lodash/js)

What would be the most straightforward way to convert the type of each element in an array on a one-by-one basis?

For example, if I have:

var a = ["2013", "72", "68", "76", "75", "76", "73"]


how could I transform
a
to the following, keeping the first item a string and converting the rest to integers:

["2013", 72, 68, 76, 75, 76, 73]


In lodash, I can manage
_.map(_.values(record), _.toNumber)
converting the entire array to numbers, but how would I map to each item in the array?

Answer

Use Array#map with the index of the loop.

var a = ["2013", "72", "68", "76", "75", "76", "73"],
		
a = a.map(function (b, i) {
    return i ? Number(b) : b;
});

console.log(a);

Comments