natalia
natalia

Reputation: 53

How to use some lodash method to check if one property doesnt match within two arrays using javascript?

i have 2 array of objects like so,

const initial = [
    {
        id: '1',
        value: '1',
    },
    {
        id: '2',
        value: '2',
    }
]

const current = [
    {
        id: '1',
        value: '3',
    },
    {
        id: '2',
        value: '2',
    },
]

these two arrays are almost the same.

i want to check if the current array has value different than the initial array with same id.

so if atleast one of the object in current has value different from the initial value then it should return true. if not false.

so in above example current array with id 1 has value 3 which is different from initial value with id '1'.

i was trying to do something like below,

const output = current.filter(item => some(initial, {id: item.id, value: !item.value}))

but this doesnt seem to be the right way. could someone help me with this. thanks.

Upvotes: 1

Views: 63

Answers (3)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

You can use the differenceWith combined with the isEqual

const initial = [
    { id: '1', value: '1' },
    { id: '2', value: '2' }
]

const current = [
    { id: '1',value: '3' },
    { id: '2',value: '2' },
]

const output = Boolean(_.differenceWith(current, initial, _.isEqual).length);
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Upvotes: 1

flyingfox
flyingfox

Reputation: 13506

Based on your code,we can compare the length to find if it has different value

let checkDiffArray = (arr1,arr2) => 
   arr1.filter(a1 => arr2.some(a2 => a2.id === a1.id && a2.value === a1.id)).length != arr2.length

const initial = [
    {
        id: '1',
        value: '1',
    },
    {
        id: '2',
        value: '2',
    }
]

const current = [
    {
        id: '1',
        value: '3',
    },
    {
        id: '2',
        value: '2',
    },
]

let checkDiffArray = (arr1,arr2) => arr1.filter(a1 => arr2.some(a2 => a2.id === a1.id && a2.value === a1.id)).length != arr2.length

console.log(checkDiffArray(initial,current))

Upvotes: 1

Majed Badawi
Majed Badawi

Reputation: 28414

  • Using Map and Array#map, save the id-value pairs of initial
  • Using Array#some, iterate over current to compare

const _isDifferent = (initial = [], current = []) => {
  const map = new Map( initial.map(({ id, value }) => ([id, value])) );
  return current.some(({ id, value }) => map.get(id) !== value);
}

const 
  initial = [ { id: '1', value: '1' }, { id: '2', value: '2' } ],
  current = [ { id: '1', value: '3' }, { id: '2', value: '2' } ];
console.log( _isDifferent(initial, current) );

Upvotes: 1

Related Questions