如何删除对象中的取值较低的值?

时间:2018-09-27 00:13:29

标签: arrays

我有这个对象数组,我需要删除重复项。删除重复项效果很好。但是,我需要添加一个条件,如果一个属性值小于另一个属性值,则取较低的值。

谁能告诉我我的病情应该是什么样的

这是我的工作代码:

function removeDuplicates(originalArray, prop) {
     var newArray = [];
     var lookupObject  = {};

     for(var i in originalArray) {
        lookupObject[originalArray[i][prop]] = originalArray[i];
     }

     for(i in lookupObject) {
         newArray.push(lookupObject[i]);
     }
      return newArray;
 }
 
 var arr = [{"id": 1, "val": 0},{"id": 2, "val": 0},{"id": 3, "val": 0},{"id": 1, "val": 1}];
 var myNewArray = removeDuplicates(arr, 'id');
 console.log(myNewArray);

2 个答案:

答案 0 :(得分:0)

您只需要比较.val属性:

 function removeDuplicates(originalArray, prop) {
   var newArray = [];
   var lookupObject = {};

   // Modified lines
   for (var i in originalArray) {
     let item = lookupObject[originalArray[i][prop]];
     if (!item || item.val > originalArray[i].val) {
       lookupObject[originalArray[i][prop]] = originalArray[i];
     }
   }

   for (i in lookupObject) {
     newArray.push(lookupObject[i]);
   }
   return newArray;
 }

 var arr = [{
   "id": 1,
   "val": 0
 }, {
   "id": 2,
   "val": 0
 }, {
   "id": 3,
   "val": 0
 }, {
   "id": 1,
   "val": 1
 }];
 var myNewArray = removeDuplicates(arr, 'id');
 console.log(myNewArray);

请注意,应避免使用for ... in遍历数组!

答案 1 :(得分:0)

您可以检查originalArray [i];已经在查找对象上,然后在已经存在的查找值和循环中的当前值之间使用min()函数来设置该值。 像这样:

function removeDuplicates(originalArray, prop) {
     var newArray = [];
     var lookupObject  = {};

     for(var i in originalArray) {
        if (originalArray[i][prop] in lookupObject) {
            lookupObject[originalArray[i][prop]] = Math.max(lookupObject[originalArray[i][prop]], originalArray[i])
        } else {
            lookupObject[originalArray[i][prop]] = originalArray[i];
        }

     }

     for(i in lookupObject) {
         newArray.push(lookupObject[i]);
     }
      return newArray;
 }

 var arr = [{"id": 1, "val": 0},{"id": 2, "val": 0},{"id": 3, "val": 0},{"id": 1, "val": 1}];
 var myNewArray = removeDuplicates(arr, 'id');
 console.log(myNewArray);