如何用字段排序创建唯一的json对象数组? [英] How to create a unique array of json objects with sort on a field?

查看:68
本文介绍了如何用字段排序创建唯一的json对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在公共id上填充以下数组,并且输出应具有唯一的最新历史记录编号

How can I filler the below array on common id and output should have unique and latest history number

const input = [{
  "id": 134116,
  "user": "admin",
  "historyno": "134116-0"
}, {
  "id": 134132,
  "user": "admin",
  "historyno": "134132-0"
}, {
  "id": 134132,
  "user": "admin",
  "historyno": "134132-1"
}, {
  "id": 134133,
  "user": "admin",
  "historyno": "134133-0"
}, {
  "id": 134133,
  "user": "admin",
  "historyno": "134133-1"
}];

let output = [];
let tempId;

for (let i = 0; i < input.length; i++) {
  if (input[i].id === tempId) {
    //do nothing
  } else {
    output.push(input[i]);
    tempId = input[i].id;
  }
}

console.log(output);

预期输出

[
  {
    "id": 134116,
    "user": "admin",
    "historyno": "134116-0"
  },
  {
    "id": 134132,
    "user": "admin",
    "historyno": "134132-1"
  },
  {
    "id": 134133,
    "user": "admin",
    "historyno": "134133-1"
  }
]

推荐答案

使用id作为键将数组简化为Map,然后通过将Map.values()迭代器扩展到数组来进行转换.

Reduce the array to a Map, using the id as key, and then convert back by spreading the Map.values() iterator to an array.

此解决方案假定该数组按历史记录编号预先排序:

This solution assumes that the array is presorted by history numbers:

const input = [{"id":134116,"user":"admin","historyno":"134116-0"},{"id":134132,"user":"admin","historyno":"134132-0"},{"id":134132,"user":"admin","historyno":"134132-1"},{"id":134133,"user":"admin","historyno":"134133-0"},{"id":134133,"user":"admin","historyno":"134133-1"}];

const output = [...input.reduce((r, o) => r.set(o.id, o), new Map).values()];

console.log(output);

如果historyno更大,则此解决方案通过仅替换地图中的当前项目来处理未排序的数组:

This solution handles unsorted arrays by only replacing the current item in the map if historyno is greater:

const input = [{"id":134116,"user":"admin","historyno":"134116-0"},{"id":134132,"user":"admin","historyno":"134132-0"},{"id":134132,"user":"admin","historyno":"134132-1"},{"id":134133,"user":"admin","historyno":"134133-0"},{"id":134133,"user":"admin","historyno":"134133-1"}];

const getHistoryNo = ({ historyno }) => +historyno.split('-')[1];

const output = [...input.reduce((r, o) => {
  const prev = r.get(o.id);
  
  if(!prev || getHistoryNo(o) > getHistoryNo(prev)) r.set(o.id, o);
  
  return r;
}, new Map).values()];

console.log(output);

这篇关于如何用字段排序创建唯一的json对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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