JavaScript-计算并删除对象数组ES6中的重复项

时间:2020-03-20 01:58:48

标签: javascript ecmascript-6 frontend

我基本上是在寻找一种简洁简洁的解决方案(可能使用ES6),以减少重复对象的数组并计算重复的数量。

例如

const items = [
   {
     id: 1,
     type: 'PEPSI',
   },
  {
     id: 1,
     type: 'PEPSI',
   },
  {
     id: 1,
     type: '7UP',
   },
  {
     id: 1,
     type: 'FANTA',
   },
  {
     id: 2,
     type: 'FANTA',
   },
  {
     id: 2,
     type: '7UP',
   },
  {
     id: 2,
     type: '7UP',
   }
];

function getItems(data, id) {
      return data.filter(x => x.id === id).map((item) => {
        const obj = {};
        obj.quantity = **I want the quantity to go here**
        obj.type = item.type;
        return obj;
      });
    }

所以运行功能getItems(items, 1)会给我:

[
 { quantity: 2, type: 'PEPSI' },
 { quantity: 1, type: '7UP' },
 { quantity: 1, type: 'FANTA' }
]

谢谢!

6 个答案:

答案 0 :(得分:0)

您可以使用以下代码:

const items = [
   {
     id: 1,
     type: 'PEPSI',
   },
  {
     id: 1,
     type: 'PEPSI',
   },
  {
     id: 1,
     type: '7UP',
   },
  {
     id: 1,
     type: 'FANTA',
   },
  {
     id: 2,
     type: 'FANTA',
   },
  {
     id: 2,
     type: '7UP',
   },
  {
     id: 2,
     type: '7UP',
   }
];

const getItems = (data) => {
    return data.reduce((a,b) => {
        const item = a.find(i => i.type === b.type);
        if(item){
            item.quantity = item.quantity + 1;
        }
        else {
            a.push({
                quantity: 0,
                type: b.type
            });
        }
        return a;
    }, []);
};
console.log(getItems(items));

const getItemsWithId = (data, id) => {
return data.reduce((a,b) => {
    if(b.id === id) {
        const item = a.find(i => i.type === b.type);
        if(item){
            item.quantity = item.quantity + 1;
        }
        else {
            a.push({
                quantity: 0,
                type: b.type
            });
        }   
    }
    return a;
}, []);
};

console.log(getItemsWithId(items, 1));

答案 1 :(得分:0)

另一种解决方案,希望对您有所帮助

    const items = [
   {
     id: 1,
     type: 'PEPSI',
   },
  {
     id: 1,
     type: 'PEPSI',
   },
  {
     id: 1,
     type: '7UP',
   },
  {
     id: 1,
     type: 'FANTA',
   },
  {
     id: 2,
     type: 'FANTA',
   },
  {
     id: 2,
     type: '7UP',
   },
  {
     id: 2,
     type: '7UP',
   }
];

function getItems(items, id){
  
      return Object.values(items.reduce((arr,curr) => {
        if(curr.id == id){
           if(arr[curr.type]){
              arr[curr.type] = {
                 ...arr[curr.type],
                 quantity: arr[curr.type].quantity + 1,
              }
           } else {
              arr[curr.type] = {
                 quantity: 1,
                 type: curr.type
           }
        }
      } else {
        arr[curr.type] = {
            quantity: 1,
            type: curr.type
        }
      }
      return arr;
     }, {}))
}
    const arr = getItems(items, 1);
    console.log(arr);

答案 2 :(得分:0)

我会做类似的事情:

private void myEntry_Focused(object sender, FocusEventArgs e)
{
    // Decete whethe in iOS platform
    if(Device.RuntimePlatform == Device.iOS)
    {
        // belong to iPhone X seriors device , the height of keyboard is 333
        if (Height > 800)
        {
            // check whether entry need to tarnslate
            if (Height - myEntry.Y - myEntry.Height < 333)
            {
                myEntry.TranslateTo(0, -333, 50);
            }
        }
        else
        {
            // belong to iPhone 6,7,8 seriors device, the height of keyboard is 258
            // check whether entry need to tarnslate
            if (Height - myEntry.Y - myEntry.Height < 258)
            {
                myEntry.TranslateTo(0, -258, 50);
            }
        }
    }

}

private void myEntry_Unfocused(object sender, FocusEventArgs e)
{
    // Decete whethe in iOS platform
    if (Device.RuntimePlatform == Device.iOS)
    {
        Console.WriteLine("unFocused");
        myEntry.TranslateTo(0, 0, 50);
    }
}

请注意,这将适用于具有任何键的任何对象。

答案 3 :(得分:0)

1.with reduce。

const items = [
          {
            id: 1,
            type: 'PEPSI',
          },
         {
            id: 1,
            type: 'PEPSI',
          },
         {
            id: 1,
            type: '7UP',
          },
         {
            id: 1,
            type: 'FANTA',
          },
         {
            id: 2,
            type: 'FANTA',
          },
         {
            id: 2,
            type: '7UP',
          },
         {
            id: 2,
            type: '7UP',
          }
       ];

const groupBy = (objectArray, property) => {
    return objectArray.reduce(function (total, obj) {
        let key = obj[property];
        if (!total[key]) {
            total[key] = 0;
        }
        total[key]+=1;
        return total;
    }, {});
 }

 let groupedArray = groupBy(items, 'type');

 console.log(groupedArray);

2。不减少。

const items = [
      {
        id: 1,
        type: 'PEPSI',
      },
     {
        id: 1,
        type: 'PEPSI',
      },
     {
        id: 1,
        type: '7UP',
      },
     {
        id: 1,
        type: 'FANTA',
      },
     {
        id: 2,
        type: 'FANTA',
      },
     {
        id: 2,
        type: '7UP',
      },
     {
        id: 2,
        type: '7UP',
      }
   ];

const compressArray = original =>{
      var compressed = [];
      var copy = original.slice(0);
      for (var i = 0; i < original.length; i++) {

        var myCount = 0;    
        // loop over every element in the copy and see if it's the same
        for (var w = 0; w < copy.length; w++) {
          if (copy[w] && original[i].type == copy[w].type) {
            // increase amount of times duplicate is found
            myCount++;
            // sets item to undefined
            delete copy[w];
          }
        }

        if (myCount > 0) {
          var a = new Object();
          a.value = original[i].type;
          a.count = myCount;
          compressed.push(a);
        }
      }

      return compressed;
};

var counter = compressArray(items);
console.log(counter);

答案 4 :(得分:0)

这里是一个它将返回您想要的内容,如果您想对许多Array执行相同的操作,则可以将其放入函数中,否则我认为它可以

const items = [
    {
      id: 1,
      type: 'PEPSI',
    },
   {
      id: 1,
      type: 'PEPSI',
    },
   {
      id: 1,
      type: '7UP',
    },
   {
      id: 1,
      type: 'FANTA',
    },
   {
      id: 2,
      type: 'FANTA',
    },
   {
      id: 2,
      type: '7UP',
    },
   {
      id: 2,
      type: '7UP',
    }
 ];
 
let tempObj = {};

for (const item of items) {
    if (tempObj[item.type] == undefined) {
        tempObj[item.type] = 1;
    }else{
        tempObj[item.type] += 1;
    }
}

//console.log(tempObj)

// And if you want to formet in a different way then 
let newTemp = [];
for (const key in tempObj) {
    let objNew = {
        quantity : tempObj[key],
        type : key
    }
    newTemp.push(objNew);
}

console.log(newTemp)

答案 5 :(得分:0)

您需要先减少数量,然后列出项目

const items  = [
   {
     id: 1,
     type: 'PEPSI',
   },
  {
     id: 1,
     type: 'PEPSI',
   },
  {
     id: 1,
     type: '7UP',
   },
  {
     id: 1,
     type: 'FANTA',
   },
  {
     id: 2,
     type: 'FANTA',
   },
  {
     id: 2,
     type: '7UP',
   },
  {
     id: 2,
     type: '7UP',
   }
];
let reducer = items.reduce(function (accumulator, currentElement) { let index = accumulator.findIndex(item=>item.id==currentElement.id && item.type==currentElement.type)
     if(index>=0){        
       accumulator[index].quantity+=1
       return [...accumulator]   
     }else{
       return [...accumulator,{...currentElement,quantity:1}]   
     }
    return accumulator
}, [])


let getItems = (items, id) => items.filter(item => item.id == id).map(item=>{return { type:item.type,quantity:item.quantity   }})

console.log(getItems(reducer,1))

相关问题