0

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 }
    ];

1 Answer 1

0

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.