Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

javascript - Remove duplicate from an array on a particular condition using jQuery

I have an array like this:

var SOItems = [
  { ID: "10", RevNo: 0 },
  { ID: "11", RevNo: 0 },
  { ID: "10", RevNo: 1 },
  { ID: "10", RevNo: 2 },
  { ID: "12", RevNo: 0 },
  { ID: "12", RevNo: 1 }
]; 

I have gone through Remove Duplicate and Get Unique and it works but not as expected because it returns the first matching value. I want those unique items whose RevNo is greater like:

SOItems = [
  { ID: "11", RevNo: 0 },
  { ID: "10", RevNo: 2 },
  { ID: "12", RevNo: 1 }
];

Please suggest me a solution


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I would use reduce which will kep track of the ids. If it has seen it, look for the rev number that is greater. After reduce is done, use Object.values() to return it to the array of objects.

var SOItems = [{ID:"10",RevNo:0},{ID:"11",RevNo:0},{ID:"10",RevNo:1},{ID:"10",RevNo:2},{ID:"12",RevNo:0},{ID:"12",RevNo:1}]; 

var result = Object.values(SOItems.reduce( function (acc, item) {
  var last = acc[item.ID];
  if (!last || item.RevNo > last.RevNo) {
    acc[item.ID] = item;
  }
  return acc;
}, {}));

console.log(result);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...