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

前端 未结 18 1330
没有蜡笔的小新
没有蜡笔的小新 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 05:14

    I came across this question while searching for a way to pick out the first item in one array that does not match any of the values in another array and managed to sort it out eventually with array.find() and array.filter() like this

    var carList= ['mercedes', 'lamborghini', 'bmw', 'honda', 'chrysler'];
    var declinedOptions = ['mercedes', 'lamborghini'];
    
    const nextOption = carList.find(car=>{
        const duplicate = declinedOptions.filter(declined=> {
          return declined === car
        })
        console.log('duplicate:',duplicate) //should list out each declined option
        if(duplicate.length === 0){//if theres no duplicate, thats the nextOption
          return car
        }
    })
    
    console.log('nextOption:', nextOption);
    //expected outputs
    //duplicate: mercedes
    //duplicate: lamborghini
    //duplicate: []
    //nextOption: bmw
    

    if you need to keep fetching an updated list before cross-checking for the next best option this should work well enough :)

提交回复
热议问题