Compare two multidimensional arrays in javascript

后端 未结 4 768
故里飘歌
故里飘歌 2021-01-23 09:18

I have two arrays:

var array_old = [{id:\"5436\", title:\"I Like you boy\"}, {id:\"5437\", title:\"Hello how are you\"}];
var array_new = [{id:\"5436\", title:\"         


        
4条回答
  •  抹茶落季
    2021-01-23 09:42

    Throwing in a wild alternative just because it works and it's ultimately easier to read (no idea about performance, but let's skip that since I'm doing it to show another way to do it)

    var ids_old = $.map(array_old, function(item) { return item.id; });
    var ids_new = $.map(array_new, function(item) { return item.id; });
    
    var duplicates = $.grep(ids_old, function(i, id) { 
        return $.inArray(id, ids_new) !== -1;
    });
    

    Be aware that the end result is that you get a list of the duplicate IDs themselves, this other alternative lets you collect the item itself:

    var ids_new = $.map(array_new, function(item) { return item.id; });
    
    var duplicates = $.grep(array_old, function(i, item) { 
        return $.inArray(item.id, ids_new) !== -1;
    });
    

    Bonus points: even if his example is pure jQuery, notice that on ECMAScript5 compliant browsers you can use the native array counterparts to achieve the same result.

提交回复
热议问题