How to get the difference between two arrays of objects in JavaScript

前端 未结 18 1337
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 04:45

I have two result sets like this:

// Result 1
[
    { value: \"0\", display: \"Jamsheer\" },
    { value: \"1\", display: \"Muhammed\" },
    { value: \"2\",         


        
18条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 04:54

    I prefer map object when it comes to big arrays.

    // create tow arrays
    array1 = Array.from({length: 400},() => ({value:Math.floor(Math.random() * 4000)}))
    array2 = Array.from({length: 400},() => ({value:Math.floor(Math.random() * 4000)}))
    
    // calc diff with some function
    console.time('diff with some');
    results = array2.filter(({ value: id1 }) => array1.some(({ value: id2 }) => id2 === id1));
    console.log('diff results ',results.length)
    console.timeEnd('diff with some');
    
    // calc diff with map object
    console.time('diff with map');
    array1Map = {};
    for(const item1 of array1){
        array1Map[item1.value] = true;
    }
    results = array2.filter(({ value: id2 }) => array1Map[id2]);
    console.log('map results ',results.length)
    console.timeEnd('diff with map');

提交回复
热议问题