Search code examples
javascriptlodash

Lodash: difference function, but based on JSON format


var b = ["text1", "text2"];
var a = [
    {name: "text3", value: 2}, 
    {name: "text4", value: 7}, 
    {name: "text1", value: 4}
];

There is a variety of Lodash functions that I tried, but none of them returning what I want to achieve.

What I want is:

var c = ["text1"]; // uniques from a compared to b
var d = [
    {name: "text3", value: 2}, 
    {name: "text4", value: 7}
]; // uniques from b compared to b

Solution

  • var c = _.reduce(a, (accumulator, item) => {
      if(b.indexOf(item.name) !== -1)
        accumulator.push(item.name)
    
      return accumulator
    }, [])
    
    var d = _.filter(a, (item) => b.indexOf(item.name) === -1)