Search code examples
javascriptreactjslodash

Comparing and returning index in lodash


var x = [{a:1, b:4,c:5}, {a:1, b:2,c:7}];
var y = [{a:1, b:2,c:6}, {a:1, b:2,c:8}];

I want to compare based on first 2 key i.e a,b and get the index if it is unequal. In above example output should be fetched as 0 since b value is nt equal. How do we achieve in javascript or Lodash ? Thank you.


Solution

  • Assuming you want to compare two objects in an array by first two keys, here's a working example. Please, feel free to elaborate.

    var x = [{a:1, b:4,c:5},{a:1, b:2,c:7}]; 
    var y = [{a:1, b:2,c:6}, {a:1, b:2,c:8}];
    
    function customizer(obj1, obj2) {
        const [a, b] = Object.keys(obj1).slice(0, 2);
    
      return obj1[a] === obj2[a] && obj1[b] === obj2[b];
    }
    
    xIsEqual = _.isEqualWith(x[0], x[1], customizer);
    yIsEqual = _.isEqualWith(y[0], y[1], customizer);
    
    console.log(xIsEqual); // false
    console.log(yIsEqual); // true