I have two dimensional array which contain element in format Name,Number. i want to convert Number part to integer
var iTicketTypeCount = [];
var sTicketTypeCount = saResponse[5].split(',');
while (sTicketTypeCount[0]) {
iTicketTypeCount.push(sTicketTypeCount.splice(0, 2));
}
My iTicketTypeCount contains
[['Firefox', '45'],['IE', '26'],['Safari', '5'],['Opera', '6'],['Others', '7']]
and i want it like
[['Firefox', 45],['IE', 26],['Safari', 5],['Opera', 6],['Others', 7]]
Only the second element should get converted into integer.
asked Aug 16, 2013 at 15:27
Shaggy
5,94030 gold badges107 silver badges170 bronze badges
4 Answers 4
Easiest imo would be using Array.map()
var arr = [['Firefox', '45'],['IE', '26'],['Safari', '5'],['Opera', '6'],['Others', '7']];
arr = arr.map(function(x) {
return [x[0], Number(x[1])];
});
answered Aug 16, 2013 at 15:29
techfoobar
66.8k14 gold badges117 silver badges138 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
metadept
Not that performance is likely to be a concern here, but I'm curious about the advantages of
map versus iterating and parsing. Is the mapped function called each time that element is accessed, or is its result stored?techfoobar
map() simply gives you a chance to process each element in an array conveniently. The plus is that this iteration is done in native code - unlike a loop we write.You can use the parseInt function to simply convert this:
$.each(arry, function(i, elem) {
arry[i] = [elem[0], parseInt(elem[1])];
});
answered Aug 16, 2013 at 15:31
metadept
7,9892 gold badges21 silver badges25 bronze badges
Comments
var iTicketTypeCount = [];
var sTicketTypeCount = saResponse[5].split(',');
while (sTicketTypeCount[0]) {
sTicketTypeCount[1] = Number(sTicketTypeCount[1]);
iTicketTypeCount.push(sTicketTypeCount.splice(0, 2));
}
You could do it without using another function.
answered Aug 16, 2013 at 15:31
kalley
18.5k2 gold badges41 silver badges37 bronze badges
Comments
Try $.each()
var arr = [['Firefox', '45'],['IE', '26'],['Safari', '5'],['Opera', '6'],['Others', '7']]
$.each(arr, function(idx, value){
value[1] = +value[1]
})
Demo: Fiddle
answered Aug 16, 2013 at 15:34
Arun P Johny
389k68 gold badges532 silver badges532 bronze badges
Comments
lang-js