根据键值

时间:2017-06-13 11:51:03

标签: javascript jquery arrays underscore.js

我有一个这样的数组:

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

我热衷于使用下划线,但也欢迎任何其他解决方案。

2 个答案:

答案 0 :(得分:2)

您可以使用哈希表和组合键作为索引的引用。



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);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以使用forEach()循环和一个对象作为thisArg参数来检查是否存在具有相同id|type的对象。

&#13;
&#13;
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)
&#13;
&#13;
&#13;