3

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?

1
  • What is the rule by which you want to keep 2013 as a string but convert the others to numbers? Commented May 20, 2016 at 14:05

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

@Yosvel Quintero No the a variable declaration should end with a comma and so it does.
@Redu, i changed the comma. it was leftover.
2

Using lodash methods map, toNumber and checking not the first in array:

var a = ["2013", "72", "68", "76", "75", "76", "73"];
var result = _.map(a, function(v) {
    return a[0] !== v ? _.toNumber(v) : v;
});
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.12.0/lodash.min.js"></script>

Comments

0

Something like this maybe :

var a = ["2013", "72", "68", "76", "75", "76", "73"]
var newArray = [];
a.map(function(d, i) {
  if (i == 0) {
    newArray.push(d)
  } else {
    newArray.push(parseInt(d, 10))
  }
  return newArray

})
console.log(newArray)

Comments

0

var a = ["2013", "72", "68", "76", "75", "76", "73"]
var b = a.map(function(item) {
  if (item.length === 4) {
    return item;
  } else {
    return parseInt(item, 10);
  }
});
console.log(b)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.