[英]Underscore.js, remove duplicates in array of objects based on key value
[英]Removing specific duplicates from object array in Underscore.js based on key values
我有一个像这样的数组:
var array = [
{"id":"A","type":"blue","rng":"50"},
{"id":"A","type":"blue","rng":"75"},
{"id":"A","type":"grey","rng":"76"},
{"id":"B","type":"blue","rng":"50"},
{"id":"B","type":"grey","rng":"85"},
{"id":"B","type":"grey","rng":"86"},
{"id":"C","type":"blue","rng":"50"},
{"id":"C","type":"grey","rng":"65"}
]
注意:对象以随机顺序排列。
我需要过滤掉重复的"id":"*","type":"blue"
和"id":"*","type":"grey"
和更高的 "rng"
。
所以最终结果是:
var result = [
{"id":"A","type":"blue","rng":"50"},
{"id":"A","type":"grey","rng":"76"},
{"id":"B","type":"blue","rng":"50"},
{"id":"B","type":"grey","rng":"86"},
{"id":"C","type":"blue","rng":"50"},
{"id":"C","type":"grey","rng":"65"}
]
我热衷于使用下划线,但也欢迎使用任何其他解决方案。
您可以使用哈希表和组合键作为对索引的引用。
var data = [{ id: "A", type: "blue", rng: "50" }, { id: "A", type: "blue", rng: "75" }, { id: "A", type: "grey", rng: "76" }, { id: "B", type: "blue", rng: "50" }, { id: "B", type: "grey", rng: "85" }, { id: "B", type: "grey", rng: "86" }, { id: "C", type: "blue", rng: "50" }, { id: "C", type: "grey", rng: "65" }], result = data.reduce(function (hash) { return function (r, o) { var key = ['id', 'type'].map(function (k) { return o[k]; }).join('|'); if (!(key in hash)) { hash[key] = r.push(o) - 1; } else if (r[hash[key]].rng < o.rng) { r[hash[key]] = o; } return r; }; }(Object.create(null)), []); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
您可以使用forEach()
循环和一个对象作为thisArg
参数来检查是否存在具有相同id|type
对象。
var array = [{"id":"A","type":"blue","rng":"50"},{"id":"A","type":"blue","rng":"75"},{"id":"A","type":"grey","rng":"76"},{"id":"B","type":"blue","rng":"50"},{"id":"B","type":"grey","rng":"85"},{"id":"B","type":"grey","rng":"86"},{"id":"C","type":"blue","rng":"50"},{"id":"C","type":"grey","rng":"65"}] var result = [] array.forEach(function(e) { // Create key with id and type var key = e.id + '|' + e.type; // Check if key exists in this object and if it doesn't create property with value of current value and push that value to result array if(!this[key]) this[key] = e, result.push(this[key]) else { // Otherwise check if rng of current element is < of rng of previous object with same key and if it is set rng to rng of current object if(e.rng < this[key].rng) this[key].rng = e.rng } }, Object.create(null)) console.log(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.