Search code examples
arraysfilterjavascript-objectsreduceon-duplicate-key

unique objects by value and extra filter within an array of objects


I am trying to get unique objects within an array of objects. Let's say the object is like below.

    values = [
      { id: 10, available: true },
      { id: 10, available: false },
      { id: 11, available: true },
      { id: 12, available: false }
    ];

unique objects should return like below: if duplicates objects contains available:true need available:true

    result = [
      { id: 10, available: true },
      { id: 11, available: true },
      { id: 12, available: false }
    ];

Solution

  • A solution to your problem.. The function myfilter() returns a array with unique id values, and if any exist with available: true it takes precedence

    var values = [
          { id: 10, available: true },
          { id: 10, available: false },
          { id: 11, available: true },
          { id: 12, available: false }
        ];
        
    function myfilter()
    {
        var filtarray=[];
        values.forEach(function(element) {
    
            var idxfound = filtarray.findIndex(function(ele2) {
                return ele2.id === element.id;
            });
            
            if (idxfound==-1)
            {
              filtarray.push(element);
            }
            else {
                if (filtarray[idxfound].available==false && element.available==true)
                filtarray[idxfound].available=true;
            }
    
        });
        
        console.log(filtarray);
        return filtarray;
    }