0

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.

4 Answers 4

5

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])];
});
Sign up to request clarification or add additional context in comments.

2 Comments

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?
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.
2

You can use the parseInt function to simply convert this:

$.each(arry, function(i, elem) {
    arry[i] = [elem[0], parseInt(elem[1])];
});

Comments

1
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.

Comments

1

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

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.