Javascript compare items in one array

后端 未结 5 1596
被撕碎了的回忆
被撕碎了的回忆 2021-01-27 00:10

Pardon my complete lack of javascript knowledge in advance, but I can\'t seem to find a good example of how to compare two arrays and create another array based the results.

5条回答
  •  离开以前
    2021-01-27 00:41

    I like the indexOf method for this. Example fiddle: http://jsfiddle.net/8MV3J/

    var good = ["someuser1", "someuser2", "someuser3"];
    var bad = [];
    var ugly = ["someuser4", "someuser1", "someuser5", "someuser2", "someuser6", "someuser3", "someuser7"];
    var i = 0;
    var li;
    
    for (i = 0; i < ugly.length; i += 1) {
        if (good.indexOf(ugly[i]) === -1) {
            bad.push(ugly[i]);
        }
    }
    
    for (i = 0; i < bad.length; i += 1) {
        li = $('
  • ').text(bad[i]); $('ul#bad').append(li); }​
提交回复
热议问题