Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

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 }
    ];
question from:https://stackoverflow.com/questions/65907935/unique-objects-by-value-and-extra-filter-within-an-array-of-objects

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...