Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
144
rated 0 times [  149] [ 5]  / answers: 1 / hits: 188856  / 12 Years ago, thu, february 28, 2013, 12:00:00

I have a string :



var str = 123, 124, 234,252;


I want to parse each item after split and increment 1. So I will have:



var arr = [124, 125, 235, 253 ];


How can I do that in NodeJS?


More From » node.js

 Answers
166

Use split and map function:



var str = 123, 124, 234,252;
var arr = str.split(,);
arr = arr.map(function (val) { return +val + 1; });


Notice +val - string is casted to a number.



Or shorter:



var str = 123, 124, 234,252;
var arr = str.split(,).map(function (val) { return +val + 1; });


edit 2015.07.29



Today I'd advise against using + operator to cast variable to a number. Instead I'd go with a more explicit but also more readable Number call:





var str = 123, 124, 234,252;
var arr = str.split(,).map(function (val) {
return Number(val) + 1;
});
console.log(arr);





edit 2017.03.09



ECMAScript 2015 introduced arrow function so it could be used instead to make the code more concise:





var str = 123, 124, 234,252;
var arr = str.split(,).map(val => Number(val) + 1);
console.log(arr);




[#79937] Wednesday, February 27, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
haylie

Total Points: 26
Total Questions: 108
Total Answers: 104

Location: France
Member since Thu, Oct 27, 2022
2 Years ago
;