Javascript es6 - How to remove duplicates in an array of objects, except the last duplicate one?

前端 未结 3 1042
野的像风
野的像风 2021-01-14 06:43

I have an array:

var arr = [
  {price: 5, amount: 100},
  {price: 3, amount: 50},
  {price: 10, amount: 20},
  {price: 3, amount: 75},
  {price: 7, amount: 1         


        
相关标签:
3条回答
  • 2021-01-14 07:29

    I'd use reduceRight and splice to remove duplicates. It doesn't create any useless intermediate objects, just a list of unique prices found along the way:

    var arr = [
      {price: 5, amount: 100},
      {price: 3, amount: 50},
      {price: 10, amount: 20},
      {price: 3, amount: 75},
      {price: 7, amount: 15},
      {price: 3, amount: 65},
      {price: 2, amount: 34}
    ]
    
    arr.reduceRight((acc, obj, i) => {
      acc[obj.price]? arr.splice(i, 1) : acc[obj.price] = true;
      return acc;
    }, Object.create(null));
    
    arr.sort((a, b) => b.price - a.price);
    
    console.log(arr)

    0 讨论(0)
  • 2021-01-14 07:45

    You can use Array.reduce to aggregate results in an array:

    var arr = [
      {price: 5, amount: 100},
      {price: 3, amount: 50},
      {price: 10, amount: 20},
      {price: 3, amount: 75},
      {price: 7, amount: 15},
      {price: 3, amount: 65},
      {price: 2, amount: 34}
    ]
    
    var results = arr.reduce<{ [price: string] : typeof arr[0] }>((p, e)=> {
        p[e.price] = e
        return p;
    }, {});
    
    var resultsAsArray = Object.keys(results)
         .map(k=>results[k])
         .sort((a, b) => b.price - a.price);
    

    You can replace typeof arr[0] with the type of the array items if one is defined.

    The idea of the solution is to acumulate the result in an object where the price is the key, if the same key is encountered multiple times, the old value is overwritten to in the end you will have only the last value for a given price.

    0 讨论(0)
  • 2021-01-14 07:48

    Use reduce to convert it an object first to remove the duplicates and last duplicate should override the previous one

    var obj = arr.reduce( ( acc, c ) =>  Object.assign(acc, {[c.price]:c.amount}) , {});
    

    Convert it back to array and sort the same

    var output = Object.keys( obj )
                  .map( s => ({ price : s, amount : obj[ s ] }) )
                  .sort( ( a, b )  => b.price - a.price );
    

    Demo

    var arr = [
      {price: 5, amount: 100},
      {price: 3, amount: 50},
      {price: 10, amount: 20},
      {price: 3, amount: 75},
      {price: 7, amount: 15},
      {price: 3, amount: 65},
      {price: 2, amount: 34}
    ];
    var obj = arr.reduce( ( acc, c ) =>  Object.assign(acc, {[c.price]:c.amount}) , {});
    var output = Object.keys( obj )
                  .map( s => ({ price : s, amount : obj[ s ] }) )
                  .sort( ( a, b )  => b.price - a.price );
    console.log( output );

    0 讨论(0)
提交回复
热议问题