Javascript es6-如何删除对象数组中的重复项(最后一个重复项除外)? [英] Javascript es6 - How to remove duplicates in an array of objects, except the last duplicate one?

查看:347
本文介绍了Javascript es6-如何删除对象数组中的重复项(最后一个重复项除外)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组:

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

我想删除价格相同的重复项,只保留最后一个重复项,然后根据价格从最高到最低对数组进行排序。这是我想要的结果:

I want to remove the duplicates which has the same price, and only keep the last duplicate one then sort the array based on price from highest to lowest. Here is the result I want:

var result = [
  {price: 10, amount: 20},
  {price : 7, amount: 15},
  {price: 5, amount: 100},
  {price: 3, amount: 65},
  {price: 2, amount: 34}
]


推荐答案

使用 reduce 将其转换为对象,首先删除重复项,最后一个重复项应覆盖前一个对象

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

演示

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

这篇关于Javascript es6-如何删除对象数组中的重复项(最后一个重复项除外)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆