JavaScript - Comparing 2 arrays - Would like to check if I'm reinventing the wheel or am I good to go? 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 &lt; data.length; x++) {   

    for (var y=0; y &lt; 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.
You should take a look at the Underscore javascript library, which contains a number of methods for comparing and manipulating arrays and objects.

I'm using the _.intersection and _.keys methods to compare your two objects. I've also taken the liberty of restructuring your arrays into objects, which I think makes more sense for what you're trying to do.

// Adds the values of keys that are the same between any two objects    
function addObjects(a, b) {
  var sameKeys = _.intersection(_.keys(a), _.keys(b)),      // Creates array of similary keys. eg ["John", "Jenny", "Amanda"]
      sumObj = {}

  // Loop through sameKeys, and add values from both objects
  for(i=0; i &lt; sameKeys.length; i++) {
    var thisKey = sameKeys[i];
    sumObj[thisKey] = a[thisKey] + b[thisKey];              // eg. sumbObj["John"] = a["John"] + b["John"] = 7 
  }

  return sumObj;
}

var firstObj = {
  "John" : 2,
  "Jenny" : 3,
  "Beavis" : 5,
  "Toby": 6,
   "Amanda": 12
}

var secondObj = {
  "John": 5,
  "Jenny": 18,
  "Amanda": 2
}


mySumObj = addObjects(firstObj, secondObj);
/* 
mySumObj = {
    "Amanda": 14,
    "Jenny": 21,
    "John": 7
}
*/


I hope this helps you. It may help if you could explain a bit more what your end goal here is.