I would like to be able to use it with IE8 or earlier, so I'm staying away from newer array methods. I'm not an expert so my code may not be the most efficient choice, but it works.
var data = [
["John", 2],
["Jenny", 3],
["John", 4],
["Beavis", 5]]
var newarr = [["John",5]];
for (var x=0; x < data.length; x++) {
for (var y=0; y < newarr.length+1; y++) {
if (typeof newarr[y] !== 'undefined') {
if (newarr[y][0] == data[x][0]) {
newarr[y][1] = (newarr[y][1] + data[x][1]);
break;
}
}
else {
newarr.push([data[x][0]]);
newarr[y][1] = data[x][1];
break;
}
}
}
alert("newarr is: " + newarr);
//if elements are similar, merge them.
Would like to find out if this is a decent way of doing it, or maybe there are other easier/less code ways of doing it. Maybe somebody sees an issue with this code that I do not. Thanks.
data.length
in the for loop for the end condition, declare length as a local variable and use that in the for loop. \$\endgroup\$