简体   繁体   English

Javascript Array 使用键值条件对唯一对象进行排序

[英]Javascript Array sorting unique object with a key value condition

I have an array我有一个数组

"datawithisNew": [
        {
            "exam_name": "MPSC",
            "isNew": false
        },
        
        {
            "exam_name": "MPSC",
            "isNew": true
        },
        {
            "exam_name": "UPSC",
            "isNew": false
        },
      
        {
            "exam_name": "RAILWAY",
            "isNew": false
        },
        {
            "exam_name": "RAILWAY",
            "isNew": false
        }]

I am trying to get a result with unique exam_name such that the resulted array of objects hold unique exam_name values also if the exam_name has atleast 1 isNew key as true, the resulted object should have the property with isNew true , if not false .我想获得独特的结果exam_name这样的对象,导致阵列保存唯一exam_name值也如果exam_name有ATLEAST 1个isNew键为真,将产生的对象应该具有与物业isNew true ,如果不是false The expected result -预期结果——

"datawithisNew": [
        {
            "exam_name": "MPSC",
            "isNew": true
        },

        {
            "exam_name": "UPSC",
            "isNew": false
        },
        {
            "exam_name": "RAILWAY",
            "isNew": false
        }]

The code i am using is-我使用的代码是-

 var helper1 = {};
    var result2 = data12.reduce(function(r, o) {
    var key = o.exam_name ;
    
    if(!helper1[key]) {
      helper1[key] = Object.assign({}, o); // create a copy of o
      r.push(helper1[key]);
    } else {
      helper1[key].exam_name_rating += o.exam_name_rating;
    }
    return r;
  }, []);

But this just return the unique exam_name object i also need isNew key if it occurs atleast true atleast once for the exam_name it should have isNew:true as true or else isNew:false但是,这只是返回唯一的exam_name对象我还需要isNew如果发生ATLEAST其关键true ATLEAST一次的exam_name它应该有isNew:true为真或者isNew:false

Use JS Array.filter to filter out duplicates使用 JS Array.filter过滤掉重复项

 const datawithisNew = [{ "exam_name": "MPSC", "isNew": false }, { "exam_name": "MPSC", "isNew": true }, { "exam_name": "UPSC", "isNew": false }, { "exam_name": "RAILWAY", "isNew": false }, { "exam_name": "RAILWAY", "isNew": false } ]; const uniqueItems = datawithisNew.filter((exam, index, self) => { return self.findIndex(e => exam.exam_name === e.exam_name) === index }).map(exam => { if (!exam.isNew && datawithisNew.find(e => e.exam_name === exam.exam_name && e.isNew)) { exam.isNew = true; } return exam; }); console.log(uniqueItems);

Call this below function with your datawithisNew as a parameter使用您的 datawithisNew 作为参数调用下面的函数

     function getUniqueExams(data){
let finalObjMap = { };
for(var i=0;i<data.length;i++){
let currentObj = data[i];
if(finalObjMap[currentObj["exam_name"]])
{
if(!finalObjMap[currentObj["isNew"]] && currentObj["isNew"])
    finalObjMap[currentObj["exam_name"]]["isNew"]=true;
}
else
{
    finalObjMap[currentObj["exam_name"]]={"isNew":currentObj["isNew"]};
}

}
let finalData=[];
Object.keys(finalObjMap).forEach((key)=>{
let tempExamObj  = { "exam_name": key , "isNew": finalObjMap[key]["isNew"]};
finalData.push(tempExamObj);

});
return finalData;
};

    var datawithisNew=[
            {
                "exam_name": "MPSC",
                "isNew": false
            },
            
            {
                "exam_name": "MPSC",
                "isNew": true
            },
            {
                "exam_name": "UPSC",
                "isNew": false
            },
          
            {
                "exam_name": "RAILWAY",
                "isNew": false
            },
            {
                "exam_name": "RAILWAY",
                "isNew": false
            }];
    console.log(getUniqueExams(datawithisNew));

You where not far from the actual solution, adding the line below solves your problem:您离实际解决方案不远,添加以下行可以解决您的问题:

helper1[key].isNew ||= o.isNew;

||= will assign a variable or property to a value if the current value is falsy.如果当前值为假, ||=会将变量或属性分配给一个值。

If you cannot use the logical OR assignment ( ||= ) operator due to it being a fairly new assignment operator you can use:如果您不能使用逻辑 OR 赋值( ||= ) 运算符,因为它是一个相当新的赋值运算符,您可以使用:

if (!helper1[key].isNew) helper1[key].isNew = o.isNew;

 const data12 = [ { "exam_name": "MPSC", "isNew": false }, { "exam_name": "MPSC", "isNew": true }, { "exam_name": "UPSC", "isNew": false }, { "exam_name": "RAILWAY", "isNew": false }, { "exam_name": "RAILWAY", "isNew": false }, ]; var helper1 = {}; var result2 = data12.reduce(function(r, o) { var key = o.exam_name ; if(!helper1[key]) { helper1[key] = Object.assign({}, o); // create a copy of o r.push(helper1[key]); } else { helper1[key].exam_name_rating += o.exam_name_rating; helper1[key].isNew ||= o.isNew; // <- added this line } return r; }, []); console.log(result2);

Since the example data does not contain the exam_name_rating property, it will be either missing, or set to NaN for the result.由于示例数据不包含exam_name_rating属性,它将丢失,或者结果设置为NaN I assume this property is available within your own data.我假设此属性在您自己的数据中可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM